package card_info_apple

import (
	"context"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"

	"github.com/gogf/gf/v2/errors/gerror"

	"kami/api/card_info_apple/v1"

	"github.com/gogf/gf/v2/errors/gcode"
)

func (c *ControllerV1) CardInfoCreate(ctx context.Context, req *v1.CardInfoCreateReq) (res *v1.CardInfoCreateRes, err error) {
	userInfo, err := service.SysAuth().LoginWithIFrameAndLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	appleAccountService := service.AppleAccount()
	dataEntity, err := appleAccountService.GetDetailByName(ctx, req.Account)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeDbOperationError, err, "获取账号失败")
		return
	}
	// 判断是否重复
	if dataEntity.Id != "" {
		err = gerror.NewCode(gcode.CodeInvalidParameter, "账号已存在")
		return
	}
	isRepeated, _ := appleAccountService.IsUnscopedTodayRepeatedByName(ctx, req.Account)
	if isRepeated {
		err = gerror.NewCode(gcode.CodeInvalidParameter, "账户名重复")
		return
	}
	err = appleAccountService.Add(ctx, &model.AppleAccountRecordInput{
		AppleAccountRecord: req.AppleAccountRecord,
		UploadUserId:       userInfo.Id,
	}, nil)
	return
}
