package api_key

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"wechat-api/ent/apikey"
	"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 GetApiKeyListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetApiKeyListLogic) GetApiKeyList(req *types.ApiKeyListReq) (*types.ApiKeyListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	var predicates []predicate.ApiKey
	predicates = append(predicates, apikey.OrganizationIDEQ(organizationId))

	data, err := l.svcCtx.DB.ApiKey.Query().Where(predicates...).WithAgent().Page(l.ctx, req.Page, req.PageSize)

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

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

	for _, v := range data.List {
		var agent types.AgentInfo
		if v.AgentID == 0 {
			agentName := "定制 AI 角色"
			agent = types.AgentInfo{
				Name: &agentName,
			}
		} else {
			if v.Edges.Agent != nil {
				agent = types.AgentInfo{
					BaseIDInfo: types.BaseIDInfo{
						Id:        &v.AgentID,
						CreatedAt: pointy.GetPointer(v.Edges.Agent.CreatedAt.UnixMilli()),
						UpdatedAt: pointy.GetPointer(v.Edges.Agent.UpdatedAt.UnixMilli()),
					},
					Name:       &v.Edges.Agent.Name,
					Role:       &v.Edges.Agent.Role,
					Status:     &v.Edges.Agent.Status,
					Background: &v.Edges.Agent.Background,
					Examples:   &v.Edges.Agent.Examples,
				}
			}
		}
		resp.Data.Data = append(resp.Data.Data,
			types.ApiKeyInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				Title:           &v.Title,
				Key:             &v.Key,
				OrganizationId:  &v.OrganizationID,
				AgentId:         &v.AgentID,
				AgentInfo:       &agent,
				CustomAgentBase: &v.CustomAgentBase,
				CustomAgentKey:  &v.CustomAgentKey,
				OpenaiBase:      &v.OpenaiBase,
				OpenaiKey:       &v.OpenaiKey,
			})
	}

	return resp, nil
}
