package feed

import (
	"context"
	"errors"
	"strconv"

	"git.huangwc.com/pig/pig-farm-controller/internal/app/controller"
	"git.huangwc.com/pig/pig-farm-controller/internal/app/dto"
	"git.huangwc.com/pig/pig-farm-controller/internal/app/service"
	"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"

	"github.com/labstack/echo/v4"
)

// NutrientController 定义了营养种类相关的控制器
type NutrientController struct {
	ctx             context.Context
	nutrientService service.NutrientService
}

// NewNutrientController 创建一个新的 NutrientController 实例
func NewNutrientController(ctx context.Context, feedManagementService service.NutrientService) *NutrientController {
	return &NutrientController{
		ctx:             ctx,
		nutrientService: feedManagementService,
	}
}

// CreateNutrient godoc
// @Summary      创建营养种类
// @Description  创建一个新的营养种类。
// @Tags         饲料管理-营养
// @Security     BearerAuth
// @Accept       json
// @Produce      json
// @Param        nutrient body dto.CreateNutrientRequest true "营养种类信息"
// @Success      200 {object} controller.Response{data=dto.NutrientResponse} "业务码为201代表创建成功"
// @Router       /api/v1/feed/nutrients [post]
func (c *NutrientController) CreateNutrient(ctx echo.Context) error {
	reqCtx, logger := logs.Trace(ctx.Request().Context(), c.ctx, "CreateNutrient")
	var req dto.CreateNutrientRequest
	const actionType = "创建营养种类"
	if err := ctx.Bind(&req); err != nil {
		logger.Errorf("%s: 参数绑定失败: %v", actionType, err)
		return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req)
	}

	resp, err := c.nutrientService.CreateNutrient(reqCtx, &req)
	if err != nil {
		logger.Errorf("%s: 服务层创建营养种类失败: %v", actionType, err)
		if errors.Is(err, service.ErrNutrientNameConflict) {
			return controller.SendErrorWithAudit(ctx, controller.CodeConflict, err.Error(), actionType, "营养种类名称已存在", req)
		}
		return controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "创建营养种类失败: "+err.Error(), actionType, "服务层创建营养种类失败", req)
	}

	logger.Infof("%s: 营养种类创建成功, ID: %d", actionType, resp.ID)
	return controller.SendSuccessWithAudit(ctx, controller.CodeCreated, "营养种类创建成功", resp, actionType, "营养种类创建成功", resp)
}

// UpdateNutrient godoc
// @Summary      更新营养种类
// @Description  根据ID更新营养种类信息。
// @Tags         饲料管理-营养
// @Security     BearerAuth
// @Accept       json
// @Produce      json
// @Param        id path int true "营养种类ID"
// @Param        nutrient body dto.UpdateNutrientRequest true "更新后的营养种类信息"
// @Success      200 {object} controller.Response{data=dto.NutrientResponse} "业务码为200代表更新成功"
// @Router       /api/v1/feed/nutrients/{id} [put]
func (c *NutrientController) UpdateNutrient(ctx echo.Context) error {
	reqCtx, logger := logs.Trace(ctx.Request().Context(), c.ctx, "UpdateNutrient")
	const actionType = "更新营养种类"
	idStr := ctx.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		logger.Errorf("%s: 营养种类ID格式错误: %v, ID: %s", actionType, err, idStr)
		return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的营养种类ID格式", actionType, "营养种类ID格式错误", idStr)
	}

	var req dto.UpdateNutrientRequest
	if err := ctx.Bind(&req); err != nil {
		logger.Errorf("%s: 参数绑定失败: %v", actionType, err)
		return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的请求体: "+err.Error(), actionType, "请求体绑定失败", req)
	}

	resp, err := c.nutrientService.UpdateNutrient(reqCtx, uint32(id), &req)
	if err != nil {
		logger.Errorf("%s: 服务层更新营养种类失败: %v, ID: %d", actionType, err, id)
		if errors.Is(err, service.ErrNutrientNotFound) {
			return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, err.Error(), actionType, "营养种类不存在", id)
		}
		if errors.Is(err, service.ErrNutrientNameConflict) {
			return controller.SendErrorWithAudit(ctx, controller.CodeConflict, err.Error(), actionType, "营养种类名称已存在", req)
		}
		return controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "更新营养种类失败: "+err.Error(), actionType, "服务层更新营养种类失败", req)
	}

	logger.Infof("%s: 营养种类更新成功, ID: %d", actionType, resp.ID)
	return controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "营养种类更新成功", resp, actionType, "营养种类更新成功", resp)
}

// DeleteNutrient godoc
// @Summary      删除营养种类
// @Description  根据ID删除营养种类。
// @Tags         饲料管理-营养
// @Security     BearerAuth
// @Produce      json
// @Param        id path int true "营养种类ID"
// @Success      200 {object} controller.Response "业务码为200代表删除成功"
// @Router       /api/v1/feed/nutrients/{id} [delete]
func (c *NutrientController) DeleteNutrient(ctx echo.Context) error {
	reqCtx, logger := logs.Trace(ctx.Request().Context(), c.ctx, "DeleteNutrient")
	const actionType = "删除营养种类"
	idStr := ctx.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		logger.Errorf("%s: 营养种类ID格式错误: %v, ID: %s", actionType, err, idStr)
		return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的营养种类ID格式", actionType, "营养种类ID格式错误", idStr)
	}

	err = c.nutrientService.DeleteNutrient(reqCtx, uint32(id))
	if err != nil {
		logger.Errorf("%s: 服务层删除营养种类失败: %v, ID: %d", actionType, err, id)
		if errors.Is(err, service.ErrNutrientNotFound) {
			return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, err.Error(), actionType, "营养种类不存在", id)
		}
		return controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "删除营养种类失败: "+err.Error(), actionType, "服务层删除营养种类失败", id)
	}

	logger.Infof("%s: 营养种类删除成功, ID: %d", actionType, id)
	return controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "营养种类删除成功", nil, actionType, "营养种类删除成功", id)
}

// GetNutrient godoc
// @Summary      获取营养种类详情
// @Description  根据ID获取单个营养种类的详细信息。
// @Tags         饲料管理-营养
// @Security     BearerAuth
// @Produce      json
// @Param        id path int true "营养种类ID"
// @Success      200 {object} controller.Response{data=dto.NutrientResponse} "业务码为200代表成功获取"
// @Router       /api/v1/feed/nutrients/{id} [get]
func (c *NutrientController) GetNutrient(ctx echo.Context) error {
	reqCtx, logger := logs.Trace(ctx.Request().Context(), c.ctx, "GetNutrient")
	const actionType = "获取营养种类详情"
	idStr := ctx.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		logger.Errorf("%s: 营养种类ID格式错误: %v, ID: %s", actionType, err, idStr)
		return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的营养种类ID格式", actionType, "营养种类ID格式错误", idStr)
	}

	resp, err := c.nutrientService.GetNutrient(reqCtx, uint32(id))
	if err != nil {
		logger.Errorf("%s: 服务层获取营养种类详情失败: %v, ID: %d", actionType, err, id)
		if errors.Is(err, service.ErrNutrientNotFound) {
			return controller.SendErrorWithAudit(ctx, controller.CodeNotFound, err.Error(), actionType, "营养种类不存在", id)
		}
		return controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取营养种类详情失败: "+err.Error(), actionType, "服务层获取营养种类详情失败", id)
	}

	logger.Infof("%s: 获取营养种类详情成功, ID: %d", actionType, id)
	return controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取营养种类详情成功", resp, actionType, "获取营养种类详情成功", resp)
}

// ListNutrients godoc
// @Summary      获取营养种类列表
// @Description  获取所有营养种类的列表，支持分页和过滤。
// @Tags         饲料管理-营养
// @Security     BearerAuth
// @Produce      json
// @Param        query query dto.ListNutrientRequest false "查询参数"
// @Success      200 {object} controller.Response{data=dto.ListNutrientResponse} "业务码为200代表成功获取列表"
// @Router       /api/v1/feed/nutrients [get]
func (c *NutrientController) ListNutrients(ctx echo.Context) error {
	reqCtx, logger := logs.Trace(ctx.Request().Context(), c.ctx, "ListNutrients")
	const actionType = "获取营养种类列表"
	var req dto.ListNutrientRequest
	if err := ctx.Bind(&req); err != nil {
		logger.Errorf("%s: 查询参数绑定失败: %v", actionType, err)
		return controller.SendErrorWithAudit(ctx, controller.CodeBadRequest, "无效的查询参数: "+err.Error(), actionType, "查询参数绑定失败", req)
	}

	resp, err := c.nutrientService.ListNutrients(reqCtx, &req)
	if err != nil {
		logger.Errorf("%s: 服务层获取营养种类列表失败: %v", actionType, err)
		return controller.SendErrorWithAudit(ctx, controller.CodeInternalError, "获取营养种类列表失败: "+err.Error(), actionType, "服务层获取营养种类列表失败", nil)
	}

	logger.Infof("%s: 获取营养种类列表成功, 数量: %d", actionType, len(resp.List))
	return controller.SendSuccessWithAudit(ctx, controller.CodeSuccess, "获取营养种类列表成功", resp, actionType, "获取营养种类列表成功", resp)
}
