package repository

import (
	"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
	"gorm.io/gorm"
)

// PigFarmRepository 定义了与猪场资产（猪舍、猪栏）相关的数据库操作接口
type PigFarmRepository interface {
	// PigHouse methods
	CreatePigHouse(house *models.PigHouse) error
	GetPigHouseByID(id uint) (*models.PigHouse, error)
	ListPigHouses() ([]models.PigHouse, error)
	// UpdatePigHouse 更新一个猪舍，返回受影响的行数和错误
	UpdatePigHouse(house *models.PigHouse) (int64, error)
	// DeletePigHouse 根据ID删除一个猪舍，返回受影响的行数和错误
	DeletePigHouse(id uint) (int64, error)
	CountPensInHouse(houseID uint) (int64, error)
}

// gormPigFarmRepository 是 PigFarmRepository 的 GORM 实现
type gormPigFarmRepository struct {
	db *gorm.DB
}

// NewGormPigFarmRepository 创建一个新的 PigFarmRepository GORM 实现实例
func NewGormPigFarmRepository(db *gorm.DB) PigFarmRepository {
	return &gormPigFarmRepository{db: db}
}

// --- PigHouse Implementation ---

// CreatePigHouse 创建一个新的猪舍
func (r *gormPigFarmRepository) CreatePigHouse(house *models.PigHouse) error {
	return r.db.Create(house).Error
}

// GetPigHouseByID 根据ID获取单个猪舍
func (r *gormPigFarmRepository) GetPigHouseByID(id uint) (*models.PigHouse, error) {
	var house models.PigHouse
	if err := r.db.First(&house, id).Error; err != nil {
		return nil, err
	}
	return &house, nil
}

// ListPigHouses 列出所有猪舍
func (r *gormPigFarmRepository) ListPigHouses() ([]models.PigHouse, error) {
	var houses []models.PigHouse
	if err := r.db.Find(&houses).Error; err != nil {
		return nil, err
	}
	return houses, nil
}

// UpdatePigHouse 更新一个猪舍，返回受影响的行数和错误
func (r *gormPigFarmRepository) UpdatePigHouse(house *models.PigHouse) (int64, error) {
	result := r.db.Model(&models.PigHouse{}).Where("id = ?", house.ID).Updates(house)
	if result.Error != nil {
		return 0, result.Error
	}
	return result.RowsAffected, nil
}

// DeletePigHouse 根据ID删除一个猪舍，返回受影响的行数和错误
func (r *gormPigFarmRepository) DeletePigHouse(id uint) (int64, error) {
	result := r.db.Delete(&models.PigHouse{}, id)
	if result.Error != nil {
		return 0, result.Error
	}
	return result.RowsAffected, nil
}

// CountPensInHouse 统计猪舍中的猪栏数量
func (r *gormPigFarmRepository) CountPensInHouse(houseID uint) (int64, error) {
	var count int64
	err := r.db.Model(&models.Pen{}).Where("house_id = ?", houseID).Count(&count).Error
	return count, err
}
