package aliyun_avatar

import (
	"context"

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

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

func (l *GetAliyunAvatarListLogic) GetAliyunAvatarList(req *types.AliyunAvatarListReq) (*types.AliyunAvatarListResp, error) {
	var predicates []predicate.AliyunAvatar
	if req.BizId != nil {
		predicates = append(predicates, aliyunavatar.BizIDContains(*req.BizId))
	}
	if req.AccessKeyId != nil {
		predicates = append(predicates, aliyunavatar.AccessKeyIDContains(*req.AccessKeyId))
	}
	if req.AccessKeySecret != nil {
		predicates = append(predicates, aliyunavatar.AccessKeySecretContains(*req.AccessKeySecret))
	}
	data, err := l.svcCtx.DB.AliyunAvatar.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data,
			types.AliyunAvatarInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				UserId:          &v.UserID,
				BizId:           &v.BizID,
				AccessKeyId:     &v.AccessKeyID,
				AccessKeySecret: &v.AccessKeySecret,
				AppId:           &v.AppID,
				TenantId:        &v.TenantID,
				Response:        &v.Response,
				Token:           &v.Token,
				SessionId:       &v.SessionID,
			})
	}

	return resp, nil
}
