package controller

import (
	"fmt"
	"opencatd-open/internal/auth"
	"opencatd-open/internal/consts"
	"opencatd-open/internal/dto"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func (a *Api) PasskeyCreateBegin(c *gin.Context) {
	userid := c.GetInt64("user_id")
	cred, err := a.webAuthService.BeginRegistration(userid)
	if err != nil {
		dto.Fail(c, 500, err.Error())
		return
	}
	dto.Success(c, cred)
}

func (a *Api) PasskeyCreateFinish(c *gin.Context) {
	userid := c.GetInt64("user_id")
	name := c.Query("name")
	if name == "" {
		name = fmt.Sprintf("User-%d-%d", userid, time.Now().Unix())
	}
	// var body protocol.CredentialCreationResponse
	// if err := c.ShouldBindJSON(&body); err != nil {
	// 	dto.Fail(c, 400, err.Error())
	// 	return
	// }

	// 获取用户凭证
	cred, err := a.webAuthService.FinishRegistration(userid, c.Request, name)
	if err != nil {
		dto.Fail(c, 500, err.Error())
		return
	}

	dto.Success(c, cred)
}

func (a *Api) ListPasskey(c *gin.Context) {
	passkeys, err := a.webAuthService.ListPasskeys(c.GetInt64("user_id"))
	if err != nil {
		dto.Fail(c, 500, err.Error())
		return
	}
	var passkeysDto []dto.Passkey
	for _, passkey := range passkeys {
		passkeysDto = append(passkeysDto, dto.Passkey{
			ID:         passkey.ID,
			Name:       passkey.Name,
			DeviceType: passkey.DeviceType,
			SignCount:  passkey.SignCount,
			LastUsedAt: passkey.LastUsedAt,
			CreatedAt:  passkey.CreatedAt,
			UpdatedAt:  passkey.UpdatedAt,
		})
	}

	dto.Success(c, passkeysDto)
}

func (a *Api) DeletePasskey(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		dto.Fail(c, 400, err.Error())
		return
	}
	if err = a.webAuthService.DeletePasskey(c.GetInt64("user_id"), id); err != nil {
		dto.Fail(c, 500, err.Error())
		return
	}
	dto.Success(c, "删除成功")
}

// 登陆
func (a *Api) PasskeyAuthBegin(c *gin.Context) {

	cred, err := a.webAuthService.BeginLogin()
	if err != nil {
		dto.Fail(c, 500, err.Error())
		return
	}
	dto.Success(c, cred)
}

func (a *Api) PasskeyAuthFinish(c *gin.Context) {
	challenge := c.Query("challenge")
	webAuthUser, err := a.webAuthService.FinishLogin(challenge, c.Request)
	if err != nil {
		dto.Fail(c, 500, err.Error())
		return
	}
	at, err := auth.GenerateTokenPair(webAuthUser.User, consts.SecretKey, consts.Day*time.Second, consts.Day*time.Second)
	if err != nil {
		dto.Fail(c, 500, err.Error())
		return
	}
	dto.Success(c, dto.Auth{
		Token:     at.AccessToken,
		ExpiresIn: time.Now().Add(consts.Day * time.Second).Unix(),
	})
}
