package shared

import (
	"strconv"

	"hyapp-admin-server/internal/middleware"
	"hyapp-admin-server/internal/repository"
	"hyapp-admin-server/internal/response"

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

type Actor struct {
	UserID      uint
	Username    string
	Permissions []string
}

func ActorFromContext(c *gin.Context) Actor {
	return Actor{
		UserID:      middleware.CurrentUserID(c),
		Username:    middleware.CurrentUsername(c),
		Permissions: middleware.CurrentPermissions(c),
	}
}

func ListOptions(c *gin.Context) repository.ListOptions {
	page, _ := strconv.Atoi(DefaultString(c.Query("page"), "1"))
	pageSize, _ := strconv.Atoi(DefaultString(c.Query("page_size"), DefaultString(c.Query("pageSize"), "10")))
	teamID, _ := strconv.ParseUint(DefaultString(c.Query("team_id"), c.Query("teamId")), 10, 64)
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 10
	}
	return repository.ListOptions{
		Page:     page,
		PageSize: pageSize,
		Keyword:  c.Query("keyword"),
		Role:     c.Query("role"),
		Status:   c.Query("status"),
		TeamID:   uint(teamID),
		Sort:     c.Query("sort"),
	}
}

func ParseID(c *gin.Context, name string) (uint, bool) {
	raw := c.Param(name)
	id, err := strconv.ParseUint(raw, 10, 64)
	if err != nil || id == 0 {
		response.BadRequest(c, "ID 参数不正确")
		return 0, false
	}
	return uint(id), true
}
