package repository

import (
	"context"
	"time"

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

	"gorm.io/gorm"
)

// MedicationLogListOptions 定义了查询用药记录时的可选参数
type MedicationLogListOptions struct {
	PigBatchID   *uint32
	MedicationID *uint32
	Reason       *models.MedicationReasonType
	OperatorID   *uint32
	StartTime    *time.Time
	EndTime      *time.Time
	OrderBy      string // 例如 "happened_at desc"
}

// MedicationLogRepository 定义了与群体用药日志模型相关的数据库操作接口。
type MedicationLogRepository interface {
	CreateMedicationLog(ctx context.Context, log *models.MedicationLog) error
	ListMedicationLogs(ctx context.Context, opts MedicationLogListOptions, page, pageSize int) ([]models.MedicationLog, int64, error)
}

// gormMedicationLogRepository 是 MedicationLogRepository 接口的 GORM 实现。
type gormMedicationLogRepository struct {
	ctx context.Context
	db  *gorm.DB
}

// NewGormMedicationLogRepository 创建一个新的 MedicationLogRepository GORM 实现实例。
func NewGormMedicationLogRepository(ctx context.Context, db *gorm.DB) MedicationLogRepository {
	return &gormMedicationLogRepository{ctx: ctx, db: db}
}

// CreateMedicationLog 创建一条新的群体用药日志记录
func (r *gormMedicationLogRepository) CreateMedicationLog(ctx context.Context, log *models.MedicationLog) error {
	repoCtx := logs.AddFuncName(ctx, r.ctx, "CreateMedicationLog")
	return r.db.WithContext(repoCtx).Create(log).Error
}

// ListMedicationLogs 实现了分页和过滤查询用药记录的功能
func (r *gormMedicationLogRepository) ListMedicationLogs(ctx context.Context, opts MedicationLogListOptions, page, pageSize int) ([]models.MedicationLog, int64, error) {
	repoCtx := logs.AddFuncName(ctx, r.ctx, "ListMedicationLogs")
	if page <= 0 || pageSize <= 0 {
		return nil, 0, ErrInvalidPagination
	}

	var results []models.MedicationLog
	var total int64

	query := r.db.WithContext(repoCtx).Model(&models.MedicationLog{})

	if opts.PigBatchID != nil {
		query = query.Where("pig_batch_id = ?", *opts.PigBatchID)
	}
	if opts.MedicationID != nil {
		query = query.Where("medication_id = ?", *opts.MedicationID)
	}
	if opts.Reason != nil {
		query = query.Where("reason = ?", *opts.Reason)
	}
	if opts.OperatorID != nil {
		query = query.Where("operator_id = ?", *opts.OperatorID)
	}
	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
}
