package repository

import (
	"time"

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

// RawMaterialPurchaseListOptions 定义了查询原料采购记录时的可选参数
type RawMaterialPurchaseListOptions struct {
	RawMaterialID *uint
	Supplier      *string
	StartTime     *time.Time // 基于 purchase_date 字段
	EndTime       *time.Time // 基于 purchase_date 字段
	OrderBy       string     // 例如 "purchase_date asc"
}

// RawMaterialStockLogListOptions 定义了查询原料库存日志时的可选参数
type RawMaterialStockLogListOptions struct {
	RawMaterialID *uint
	SourceType    *models.StockLogSourceType
	SourceID      *uint
	StartTime     *time.Time // 基于 happened_at 字段
	EndTime       *time.Time // 基于 happened_at 字段
	OrderBy       string     // 例如 "happened_at asc"
}

// FeedUsageRecordListOptions 定义了查询饲料使用记录时的可选参数
type FeedUsageRecordListOptions struct {
	PenID         *uint
	FeedFormulaID *uint
	OperatorID    *uint
	StartTime     *time.Time // 基于 recorded_at 字段
	EndTime       *time.Time // 基于 recorded_at 字段
	OrderBy       string     // 例如 "recorded_at asc"
}

// RawMaterialRepository 定义了与原料相关的数据库操作接口
type RawMaterialRepository interface {
	ListRawMaterialPurchases(opts RawMaterialPurchaseListOptions, page, pageSize int) ([]models.RawMaterialPurchase, int64, error)
	ListRawMaterialStockLogs(opts RawMaterialStockLogListOptions, page, pageSize int) ([]models.RawMaterialStockLog, int64, error)
	ListFeedUsageRecords(opts FeedUsageRecordListOptions, page, pageSize int) ([]models.FeedUsageRecord, int64, error)
}

// gormRawMaterialRepository 是 RawMaterialRepository 的 GORM 实现
type gormRawMaterialRepository struct {
	db *gorm.DB
}

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

// ListRawMaterialPurchases 实现了分页和过滤查询原料采购记录的功能
func (r *gormRawMaterialRepository) ListRawMaterialPurchases(opts RawMaterialPurchaseListOptions, page, pageSize int) ([]models.RawMaterialPurchase, int64, error) {
	if page <= 0 || pageSize <= 0 {
		return nil, 0, ErrInvalidPagination
	}

	var results []models.RawMaterialPurchase
	var total int64

	query := r.db.Model(&models.RawMaterialPurchase{})

	if opts.RawMaterialID != nil {
		query = query.Where("raw_material_id = ?", *opts.RawMaterialID)
	}
	if opts.Supplier != nil {
		query = query.Where("supplier LIKE ?", "%"+*opts.Supplier+"%")
	}
	if opts.StartTime != nil {
		query = query.Where("purchase_date >= ?", *opts.StartTime)
	}
	if opts.EndTime != nil {
		query = query.Where("purchase_date <= ?", *opts.EndTime)
	}

	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	orderBy := "purchase_date DESC"
	if opts.OrderBy != "" {
		orderBy = opts.OrderBy
	}
	query = query.Order(orderBy).Preload("RawMaterial")

	offset := (page - 1) * pageSize
	err := query.Limit(pageSize).Offset(offset).Find(&results).Error

	return results, total, err
}

// ListRawMaterialStockLogs 实现了分页和过滤查询原料库存日志的功能
func (r *gormRawMaterialRepository) ListRawMaterialStockLogs(opts RawMaterialStockLogListOptions, page, pageSize int) ([]models.RawMaterialStockLog, int64, error) {
	if page <= 0 || pageSize <= 0 {
		return nil, 0, ErrInvalidPagination
	}

	var results []models.RawMaterialStockLog
	var total int64

	query := r.db.Model(&models.RawMaterialStockLog{})

	if opts.RawMaterialID != nil {
		query = query.Where("raw_material_id = ?", *opts.RawMaterialID)
	}
	if opts.SourceType != nil {
		query = query.Where("source_type = ?", *opts.SourceType)
	}
	if opts.SourceID != nil {
		query = query.Where("source_id = ?", *opts.SourceID)
	}
	if opts.StartTime != nil {
		query = query.Where("happened_at >= ?", *opts.StartTime)
	}
	if opts.EndTime != nil {
		query = query.Where("happened_at <= ?", *opts.EndTime)
	}

	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	orderBy := "happened_at DESC"
	if opts.OrderBy != "" {
		orderBy = opts.OrderBy
	}
	query = query.Order(orderBy)

	offset := (page - 1) * pageSize
	err := query.Limit(pageSize).Offset(offset).Find(&results).Error

	return results, total, err
}

// ListFeedUsageRecords 实现了分页和过滤查询饲料使用记录的功能
func (r *gormRawMaterialRepository) ListFeedUsageRecords(opts FeedUsageRecordListOptions, page, pageSize int) ([]models.FeedUsageRecord, int64, error) {
	if page <= 0 || pageSize <= 0 {
		return nil, 0, ErrInvalidPagination
	}

	var results []models.FeedUsageRecord
	var total int64

	query := r.db.Model(&models.FeedUsageRecord{})

	if opts.PenID != nil {
		query = query.Where("pen_id = ?", *opts.PenID)
	}
	if opts.FeedFormulaID != nil {
		query = query.Where("feed_formula_id = ?", *opts.FeedFormulaID)
	}
	if opts.OperatorID != nil {
		query = query.Where("operator_id = ?", *opts.OperatorID)
	}
	if opts.StartTime != nil {
		query = query.Where("recorded_at >= ?", *opts.StartTime)
	}
	if opts.EndTime != nil {
		query = query.Where("recorded_at <= ?", *opts.EndTime)
	}

	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	orderBy := "recorded_at DESC"
	if opts.OrderBy != "" {
		orderBy = opts.OrderBy
	}
	query = query.Order(orderBy).Preload("Pen").Preload("FeedFormula")

	offset := (page - 1) * pageSize
	err := query.Limit(pageSize).Offset(offset).Find(&results).Error

	return results, total, err
}
