package http

import (
	"strings"
	"time"

	"quyun/app/models"
	"quyun/database/schemas/public/model"

	"github.com/gofiber/fiber/v3"
)

// @provider
type users struct{}

type UserInfo struct {
	ID        int64     `json:"id,omitempty"`
	CreatedAt time.Time `json:"created_at,omitempty"`
	Username  string    `json:"username,omitempty"`
	Avatar    string    `json:"avatar,omitempty"`
	Balance   int64     `json:"balance"`
}

// @Router	/users/profile [get]
// @Bind	user local
func (ctl *users) Profile(ctx fiber.Ctx, user *model.Users) (*UserInfo, error) {
	return &UserInfo{
		ID:        user.ID,
		CreatedAt: user.CreatedAt,
		Username:  user.Username,
		Avatar:    *user.Avatar,
		Balance:   user.Balance,
	}, nil
}

type ProfileForm struct {
	Username string `json:"username" validate:"required"`
}

// Update
//
//	@Router	/users/username [put]
//	@Bind	user local
//	@Bind	form body
func (ctl *users) Update(ctx fiber.Ctx, user *model.Users, form *ProfileForm) error {
	username := strings.TrimSpace(form.Username)
	if len([]rune(username)) > 12 {
		return fiber.NewError(fiber.StatusBadRequest, "Username exceeds maximum length of 12 characters")
	}

	if username == "" {
		return fiber.NewError(fiber.StatusBadRequest, "Username cannot be empty")
	}

	if err := models.Users.UpdateUsername(ctx.Context(), user.ID, username); err != nil {
		return err
	}
	return nil
}
