package contact

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

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

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

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

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

func (l *GetWhatsappContactLogic) GetWhatsappContact(req *types.IDReq) (resp *types.ContactInfoResp, err error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	data, err := l.svcCtx.DB.Contact.Query().
		Where(
			contact.IDEQ(req.Id),                   // Filter by ID
			contact.OrganizationID(organizationId), // Additional filter by organizationId
			contact.Ctype(2),
		).
		WithContactRelationships(func(query *ent.LabelRelationshipQuery) {
			query.WithLabels()
		}).
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	labelRelationships := make([]types.ContactLabelList, 0)
	if data.Edges.ContactRelationships != nil {
		for _, lr := range data.Edges.ContactRelationships {
			if lr.Edges.Labels == nil {
				continue
			}
			labelRelationships = append(labelRelationships, types.ContactLabelList{
				Label: &lr.Edges.Labels.Name,
				Value: &lr.LabelID,
			})
		}
	}

	return &types.ContactInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.ContactInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &data.ID,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			Phone:              &data.Phone,
			Cc:                 &data.Cc,
			Markname:           &data.Markname,
			OrganizationId:     &data.OrganizationID,
			Ctype:              &data.Ctype,
			Cname:              &data.Cname,
			Sex:                &data.Sex,
			Cage:               &data.Cage,
			Carea:              &data.Carea,
			Cbirthday:          &data.Cbirthday,
			Cbirtharea:         &data.Cbirtharea,
			CidcardNo:          &data.CidcardNo,
			Ctitle:             &data.Ctitle,
			LabelRelationships: labelRelationships,
		},
	}, nil
}
