package openapi

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 OpenapiGetContactListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *OpenapiGetContactListLogic) OpenapiGetContactList(req *types.WxidReq) (resp *types.ContactListResp, err error) {
	data, err := l.svcCtx.DB.Contact.Query().Where(contact.WxWxid(req.Wxid)).All(l.ctx)

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

	resp = &types.ContactListResp{}
	resp.Msg = errormsg.Success
	resp.Data.Total = uint64(len(data))
	for _, v := range data {
		resp.Data.Data = append(resp.Data.Data,
			types.ContactInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Status:    &v.Status,
				WxWxid:    &v.WxWxid,
				Type:      &v.Type,
				Wxid:      &v.Wxid,
				Account:   &v.Account,
				Nickname:  &v.Nickname,
				Markname:  &v.Markname,
				Headimg:   &v.Headimg,
				Sex:       &v.Sex,
				Starrole:  &v.Starrole,
				Dontseeit: &v.Dontseeit,
				Dontseeme: &v.Dontseeme,
				Lag:       &v.Lag,
				Gid:       &v.Gid,
				Gname:     &v.Gname,
				V3:        &v.V3,
			})
	}

	return resp, nil
}
