package token

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"wechat-api/ent/predicate"
	"wechat-api/ent/token"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

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

func (l *GetApiTokenListLogic) GetApiTokenList(req *types.TokenListReq) (*types.TokenListResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)

	var predicates []predicate.Token
	predicates = append(predicates, token.OrganizationID(organizationId))

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

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

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

	for _, v := range data.List {
		departmentInfo, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: v.OrganizationID})
		if err != nil {
			l.Error("获取部门信息失败", err)
		}
		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,
				}
			}
		}

		expireAtStr := v.ExpireAt.Format("2006-01-02 15:04:05")
		resp.Data.Data = append(resp.Data.Data,
			types.TokenInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				ExpireAt:         pointy.GetUnixMilliPointer(v.ExpireAt.UnixMilli()),
				ExpireAtStr:      &expireAtStr,
				Token:            &v.Token,
				Mac:              &v.MAC,
				OrganizationId:   &v.OrganizationID,
				OrganizationName: departmentInfo.Name,
				AgentId:          &v.AgentID,
				AgentInfo:        &agent,
				CustomAgentBase:  &v.CustomAgentBase,
				CustomAgentKey:   &v.CustomAgentKey,
				OpenaiBase:       &v.OpenaiBase,
				OpenaiKey:        &v.OpenaiKey,
			})
	}

	return resp, nil
}
