package admin

import (
	"strconv"

	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	enterpriseService "github.com/break/junhong_cmp_fiber/internal/service/enterprise"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

type EnterpriseHandler struct {
	service *enterpriseService.Service
}

func NewEnterpriseHandler(service *enterpriseService.Service) *EnterpriseHandler {
	return &EnterpriseHandler{service: service}
}

func (h *EnterpriseHandler) Create(c *fiber.Ctx) error {
	var req dto.CreateEnterpriseReq
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	result, err := h.service.Create(c.UserContext(), &req)
	if err != nil {
		return err
	}

	return response.Success(c, result)
}

func (h *EnterpriseHandler) List(c *fiber.Ctx) error {
	var req dto.EnterpriseListReq
	if err := c.QueryParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	result, err := h.service.List(c.UserContext(), &req)
	if err != nil {
		return err
	}

	return response.SuccessWithPagination(c, result.Items, result.Total, result.Page, result.Size)
}

func (h *EnterpriseHandler) Update(c *fiber.Ctx) error {
	idStr := c.Params("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的企业ID")
	}

	var req dto.UpdateEnterpriseBody
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	result, err := h.service.Update(c.UserContext(), uint(id), &req)
	if err != nil {
		return err
	}

	return response.Success(c, result)
}

func (h *EnterpriseHandler) UpdateStatus(c *fiber.Ctx) error {
	idStr := c.Params("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的企业ID")
	}

	var req dto.UpdateEnterpriseStatusBody
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	if err := h.service.UpdateStatus(c.UserContext(), uint(id), req.Status); err != nil {
		return err
	}

	return response.Success(c, nil)
}

func (h *EnterpriseHandler) UpdatePassword(c *fiber.Ctx) error {
	idStr := c.Params("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return errors.New(errors.CodeInvalidParam, "无效的企业ID")
	}

	var req dto.UpdateEnterprisePasswordBody
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	if err := h.service.UpdatePassword(c.UserContext(), uint(id), req.Password); err != nil {
		return err
	}

	return response.Success(c, nil)
}
