package team

import (
	"errors"
	"fmt"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"hyapp-admin-server/internal/modules/shared"
	"hyapp-admin-server/internal/repository"
	"hyapp-admin-server/internal/response"
)

type Handler struct {
	service *Service
	audit   shared.OperationLogger
}

func New(store *repository.Store, audit shared.OperationLogger) *Handler {
	return &Handler{service: NewService(store), audit: audit}
}

func (h *Handler) ListTeams(c *gin.Context) {
	teams, err := h.service.ListTeams(c.Query("keyword"))
	if err != nil {
		response.ServerError(c, "获取团队失败")
		return
	}
	response.OK(c, teamDTOs(teams))
}

func (h *Handler) CreateTeam(c *gin.Context) {
	var req teamRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "团队参数不正确")
		return
	}
	team, err := h.service.CreateTeam(Input{Name: req.Name, ParentID: req.ParentID, Description: req.Description, Sort: req.Sort})
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLog(c, h.audit, "create-team", "admin_teams", "success", team.Name)
	response.Created(c, teamDTO(*team))
}

func (h *Handler) UpdateTeam(c *gin.Context) {
	id, ok := shared.ParseID(c, "team_id")
	if !ok {
		return
	}
	var req teamRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "团队参数不正确")
		return
	}
	team, err := h.service.UpdateTeam(id, Input{Name: req.Name, ParentID: req.ParentID, Description: req.Description, Sort: req.Sort})
	if errors.Is(err, gorm.ErrRecordNotFound) {
		response.NotFound(c, "团队不存在")
		return
	}
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLog(c, h.audit, "update-team", "admin_teams", "success", fmt.Sprintf("%d:%s", id, team.Name))
	response.OK(c, teamDTO(*team))
}

func (h *Handler) ListTeamUsers(c *gin.Context) {
	id, ok := shared.ParseID(c, "team_id")
	if !ok {
		return
	}
	options := shared.ListOptions(c)
	users, total, err := h.service.ListTeamUsers(shared.ActorFromContext(c), id, options)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		response.NotFound(c, "团队不存在")
		return
	}
	if err != nil {
		response.ServerError(c, "获取团队用户失败")
		return
	}
	response.OK(c, response.Page{Items: shared.UserDTOs(users), Page: options.Page, PageSize: options.PageSize, Total: total})
}
