package label_relationship

import (
	"context"
	"wechat-api/ent/labelrelationship"

	"wechat-api/ent/predicate"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetLabelRelationshipListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetLabelRelationshipListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLabelRelationshipListLogic {
	return &GetLabelRelationshipListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetLabelRelationshipListLogic) GetLabelRelationshipList(req *types.LabelRelationshipListReq) (*types.LabelRelationshipListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	var predicates []predicate.LabelRelationship
	predicates = append(predicates, labelrelationship.OrganizationIDEQ(organizationId))
	data, err := l.svcCtx.DB.LabelRelationship.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	resp := &types.LabelRelationshipListResp{}
	resp.Msg = errormsg.Success
	resp.Data.Total = data.PageDetails.Total

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.LabelRelationshipInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Status:    &v.Status,
				LabelId:   &v.LabelID,
				ContactId: &v.ContactID,
			})
	}

	return resp, nil
}
