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"
)

// PigTransferLogListOptions 定义了查询猪只迁移日志时的可选参数
type PigTransferLogListOptions struct {
	PigBatchID    *uint32
	PenID         *uint32
	TransferType  *models.PigTransferType // 迁移类型
	OperatorID    *uint32
	CorrelationID *string
	StartTime     *time.Time // 基于 transfer_time 字段
	EndTime       *time.Time // 基于 transfer_time 字段
	OrderBy       string     // 例如 "transfer_time desc"
}

// PigTransferLogRepository 定义了猪只迁移日志数据持久化的接口。
type PigTransferLogRepository interface {
	// CreatePigTransferLog 在数据库中创建一条猪只迁移日志记录。
	CreatePigTransferLog(ctx context.Context, tx *gorm.DB, log *models.PigTransferLog) error

	// GetLogsForPenSince 获取指定猪栏自特定时间点以来的所有迁移日志，按时间倒序排列。
	GetLogsForPenSince(ctx context.Context, tx *gorm.DB, penID uint32, since time.Time) ([]*models.PigTransferLog, error)

	// ListPigTransferLogs 支持分页和过滤的猪只迁移日志列表查询
	ListPigTransferLogs(ctx context.Context, opts PigTransferLogListOptions, page, pageSize int) ([]models.PigTransferLog, int64, error)
}

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

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

// CreatePigTransferLog 实现了在数据库中创建猪只迁移日志记录的逻辑。
func (r *gormPigTransferLogRepository) CreatePigTransferLog(ctx context.Context, tx *gorm.DB, log *models.PigTransferLog) error {
	repoCtx := logs.AddFuncName(ctx, r.ctx, "CreatePigTransferLog")
	return tx.WithContext(repoCtx).Create(log).Error
}

// GetLogsForPenSince 实现了获取猪栏自特定时间点以来所有迁移日志的逻辑。
func (r *gormPigTransferLogRepository) GetLogsForPenSince(ctx context.Context, tx *gorm.DB, penID uint32, since time.Time) ([]*models.PigTransferLog, error) {
	repoCtx := logs.AddFuncName(ctx, r.ctx, "GetLogsForPenSince")
	var logs []*models.PigTransferLog
	err := tx.WithContext(repoCtx).Where("pen_id = ? AND transfer_time >= ?", penID, since).Order("transfer_time DESC").Find(&logs).Error
	return logs, err
}

// ListPigTransferLogs 实现了分页和过滤查询猪只迁移日志的功能
func (r *gormPigTransferLogRepository) ListPigTransferLogs(ctx context.Context, opts PigTransferLogListOptions, page, pageSize int) ([]models.PigTransferLog, int64, error) {
	repoCtx := logs.AddFuncName(ctx, r.ctx, "ListPigTransferLogs")
	if page <= 0 || pageSize <= 0 {
		return nil, 0, ErrInvalidPagination
	}

	var results []models.PigTransferLog
	var total int64

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

	if opts.PigBatchID != nil {
		query = query.Where("pig_batch_id = ?", *opts.PigBatchID)
	}
	if opts.PenID != nil {
		query = query.Where("pen_id = ?", *opts.PenID)
	}
	if opts.TransferType != nil {
		query = query.Where("type = ?", *opts.TransferType)
	}
	if opts.OperatorID != nil {
		query = query.Where("operator_id = ?", *opts.OperatorID)
	}
	if opts.CorrelationID != nil {
		query = query.Where("correlation_id = ?", *opts.CorrelationID)
	}
	if opts.StartTime != nil {
		query = query.Where("transfer_time >= ?", *opts.StartTime)
	}
	if opts.EndTime != nil {
		query = query.Where("transfer_time <= ?", *opts.EndTime)
	}

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

	orderBy := "transfer_time 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
}
