package camel_oil

import (
	"context"

	"github.com/gogf/gf/v2/errors/gcode"
	v1 "kami/api/camel_oil/v1"
	"kami/api/commonApi"
	"kami/internal/consts"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"
)

func (c *ControllerV1) ListTokens(ctx context.Context, req *v1.ListTokensReq) (res *v1.ListTokensRes, err error) {
	// 首先尝试管理员权限验证（IFrame登录）
	_, adminErr := service.SysAuth().LoginWithIFrameAndLogin(ctx)
	if adminErr != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "登录校验失败")
	}

	// 调用服务层方法，它会根据当前用户类型自动筛选数据
	// 管理员：可以查看所有token（包括用户创建和管理员创建的）
	// 普通用户：只能查看自己创建的token
	tokens, total, err := service.CamelOil().ListTokensWithPagination(ctx, &model.CamelOilTokenListInput{
		CommonPageReq: req.CommonPageReq,
		Name:          req.Name,
		Status:        req.Status,
	})
	if err != nil {
		return nil, err
	}
	tokenInfos := make([]v1.TokenInfo, 0, len(tokens))
	for _, token := range tokens {
		tokenInfos = append(tokenInfos, v1.TokenInfo{
			Id:                  token.Id,
			UserId:              token.UserId,
			Name:                token.Name,
			LoginToken:          token.LoginToken,
			Phone:               token.Phone,
			Status:              consts.CamelOilTokenStatus(token.Status),
			BindCount:           token.BindCount,
			TotalBindAmount:     token.TotalBindAmount.InexactFloat64(),
			TotalRechargeAmount: token.TotalRechargeAmount.InexactFloat64(),
			RechargeLimitAmount: token.RechargeLimitAmount.InexactFloat64(),
			RechargeLimitCount:  token.RechargeLimitCount,
			LastBindAt:          token.LastBindAt,
			LastUsedAt:          token.LastUsedAt,
			Remark:              token.Remark,
			CreatedAt:           token.CreatedAt,
			UpdatedAt:           token.UpdatedAt,
		})
	}
	return &v1.ListTokensRes{
		CommonPageRes: commonApi.CommonPageRes[v1.TokenInfo]{
			Total: total,
			CommonDataRes: commonApi.CommonDataRes[v1.TokenInfo]{
				List: tokenInfos,
			},
		},
	}, nil
}
