package contact

import (
	"context"
	"wechat-api/ent/contact"
	"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 GetContactByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *GetContactByIdLogic) GetContactById(req *types.IDReq) (*types.ContactInfoResp, 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
		).
		Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	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()),
			},
			Status:    &data.Status,
			WxWxid:    &data.WxWxid,
			Type:      &data.Type,
			Wxid:      &data.Wxid,
			Account:   &data.Account,
			Nickname:  &data.Nickname,
			Markname:  &data.Markname,
			Headimg:   &data.Headimg,
			Sex:       &data.Sex,
			Starrole:  &data.Starrole,
			Dontseeit: &data.Dontseeit,
			Dontseeme: &data.Dontseeme,
			Lag:       &data.Lag,
			Gid:       &data.Gid,
			Gname:     &data.Gname,
			V3:        &data.V3,
		},
	}, nil
}
