package label

import (
	"context"
	"errors"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"wechat-api/ent"
	"wechat-api/ent/label"
	"wechat-api/ent/predicate"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *GetLabelContactsLogic) GetLabelContacts(req *types.LabelListReq) (*types.LabelListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	if len(req.LabelIDs) == 0 {
		return nil, errors.New("label id list cannot be empty")
	}
	var predicates []predicate.Label
	predicates = append(predicates, label.OrganizationIDEQ(organizationId))
	if len(req.LabelIDs) > 0 {
		predicates = append(predicates, label.IDIn(req.LabelIDs...))
	}
	if req.Type != nil {
		predicates = append(predicates, label.TypeEQ(*req.Type))
	}
	if req.Name != nil {
		predicates = append(predicates, label.NameContains(*req.Name))
	}
	if req.From != nil {
		predicates = append(predicates, label.FromEQ(*req.From))
	}
	if req.Mode != nil {
		predicates = append(predicates, label.ModeEQ(*req.Mode))
	}

	data, err := l.svcCtx.DB.Label.Query().Where(predicates...).WithLabelRelationships(func(query *ent.LabelRelationshipQuery) {
		query.WithContacts()
	}).Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		labelRelationships := make([]types.LabelRelationshipInfo, 0)
		if v.Edges.LabelRelationships != nil {
			for _, lr := range v.Edges.LabelRelationships {
				labelRelationships = append(labelRelationships, types.LabelRelationshipInfo{
					BaseIDInfo: types.BaseIDInfo{
						Id:        &lr.ID,
						CreatedAt: pointy.GetPointer(lr.CreatedAt.UnixMilli()),
						UpdatedAt: pointy.GetPointer(lr.UpdatedAt.UnixMilli()),
					},
					Status:    &lr.Status,
					LabelId:   &lr.LabelID,
					ContactId: &lr.ContactID,
					Contact:   convertContactToContactInfo(lr.Edges.Contacts),
				})
			}
		}
		resp.Data.Data = append(resp.Data.Data,
			types.LabelInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Status:             &v.Status,
				Type:               &v.Type,
				Name:               &v.Name,
				From:               &v.From,
				Mode:               &v.Mode,
				Conditions:         &v.Conditions,
				LabelRelationships: labelRelationships,
			})
	}

	return resp, nil
}
