package recipe

import (
	"context"
	"errors"
	"fmt"

	"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
	"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
	"git.huangwc.com/pig/pig-farm-controller/internal/infra/repository"

	"gorm.io/gorm"
)

// 定义领域特定的错误
var (
	ErrNutrientNameConflict = fmt.Errorf("营养种类名称已存在")
	ErrNutrientNotFound     = fmt.Errorf("营养种类不存在")
)

// NutrientService 定义了营养种类领域的核心业务服务接口
type NutrientService interface {
	CreateNutrient(ctx context.Context, name, description string) (*models.Nutrient, error)
	UpdateNutrient(ctx context.Context, id uint32, name, description string) (*models.Nutrient, error)
	DeleteNutrient(ctx context.Context, id uint32) error
	GetNutrient(ctx context.Context, id uint32) (*models.Nutrient, error)
	ListNutrients(ctx context.Context, opts repository.NutrientListOptions, page, pageSize int) ([]models.Nutrient, int64, error)
}

// nutrientServiceImpl 是 NutrientService 的实现
type nutrientServiceImpl struct {
	ctx          context.Context
	nutrientRepo repository.NutrientRepository
}

// NewNutrientService 创建一个新的 NutrientService 实例
func NewNutrientService(ctx context.Context, nutrientRepo repository.NutrientRepository) NutrientService {
	return &nutrientServiceImpl{
		ctx:          ctx,
		nutrientRepo: nutrientRepo,
	}
}

// CreateNutrient 实现了创建营养种类的核心业务逻辑
func (s *nutrientServiceImpl) CreateNutrient(ctx context.Context, name, description string) (*models.Nutrient, error) {
	serviceCtx := logs.AddFuncName(ctx, s.ctx, "CreateNutrient")

	// 检查名称是否已存在
	existing, err := s.nutrientRepo.GetNutrientByName(serviceCtx, name)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { // 只有不是记录未找到的错误才返回
		return nil, fmt.Errorf("检查营养种类名称失败: %w", err)
	}
	if existing != nil {
		return nil, ErrNutrientNameConflict
	}

	nutrient := &models.Nutrient{
		Name:        name,
		Description: description,
	}

	if err := s.nutrientRepo.CreateNutrient(serviceCtx, nutrient); err != nil {
		return nil, fmt.Errorf("创建营养种类失败: %w", err)
	}

	return nutrient, nil
}

// UpdateNutrient 实现了更新营养种类的核心业务逻辑
func (s *nutrientServiceImpl) UpdateNutrient(ctx context.Context, id uint32, name, description string) (*models.Nutrient, error) {
	serviceCtx := logs.AddFuncName(ctx, s.ctx, "UpdateNutrient")

	// 检查要更新的实体是否存在
	nutrient, err := s.nutrientRepo.GetNutrientByID(serviceCtx, id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) { // 如果是记录未找到错误，则返回领域错误
			return nil, ErrNutrientNotFound
		}
		return nil, fmt.Errorf("获取待更新的营养种类失败: %w", err)
	}

	// 如果名称有变动，检查新名称是否与其它记录冲突
	if nutrient.Name != name {
		existing, err := s.nutrientRepo.GetNutrientByName(serviceCtx, name)
		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, fmt.Errorf("检查新的营养种类名称失败: %w", err)
		}
		if existing != nil && existing.ID != id {
			return nil, ErrNutrientNameConflict
		}
	}

	nutrient.Name = name
	nutrient.Description = description

	if err := s.nutrientRepo.UpdateNutrient(serviceCtx, nutrient); err != nil {
		return nil, fmt.Errorf("更新营养种类失败: %w", err)
	}

	return nutrient, nil
}

// DeleteNutrient 实现了删除营养种类的核心业务逻辑
func (s *nutrientServiceImpl) DeleteNutrient(ctx context.Context, id uint32) error {
	serviceCtx := logs.AddFuncName(ctx, s.ctx, "DeleteNutrient")

	// 检查实体是否存在
	_, err := s.nutrientRepo.GetNutrientByID(serviceCtx, id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return ErrNutrientNotFound
		}
		return fmt.Errorf("获取待删除的营养种类失败: %w", err)
	}

	if err := s.nutrientRepo.DeleteNutrient(serviceCtx, id); err != nil {
		return fmt.Errorf("删除营养种类失败: %w", err)
	}

	return nil
}

// GetNutrient 实现了获取单个营养种类的逻辑
func (s *nutrientServiceImpl) GetNutrient(ctx context.Context, id uint32) (*models.Nutrient, error) {
	serviceCtx := logs.AddFuncName(ctx, s.ctx, "GetNutrient")

	nutrient, err := s.nutrientRepo.GetNutrientByID(serviceCtx, id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, ErrNutrientNotFound
		}
		return nil, fmt.Errorf("获取营养种类失败: %w", err)
	}
	return nutrient, nil
}

// ListNutrients 实现了列出营养种类的逻辑
func (s *nutrientServiceImpl) ListNutrients(ctx context.Context, opts repository.NutrientListOptions, page, pageSize int) ([]models.Nutrient, int64, error) {
	serviceCtx := logs.AddFuncName(ctx, s.ctx, "ListNutrients")

	nutrients, total, err := s.nutrientRepo.ListNutrients(serviceCtx, opts, page, pageSize)
	if err != nil {
		return nil, 0, fmt.Errorf("获取营养种类列表失败: %w", err)
	}
	return nutrients, total, nil
}
