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

// DeviceCommandLogListOptions 定义了查询设备命令日志时的可选参数
type DeviceCommandLogListOptions struct {
	DeviceID        *uint32
	ReceivedSuccess *bool
	StartTime       *time.Time // 基于 sent_at 字段
	EndTime         *time.Time // 基于 sent_at 字段
	OrderBy         string     // 例如 "sent_at asc"
}

// DeviceCommandLogRepository 定义了设备下行命令历史记录的数据访问接口
type DeviceCommandLogRepository interface {
	Create(ctx context.Context, record *models.DeviceCommandLog) error
	FindByMessageID(ctx context.Context, messageID string) (*models.DeviceCommandLog, error)
	UpdateAcknowledgedAt(ctx context.Context, messageID string, acknowledgedAt time.Time, receivedSuccess bool) error
	// List 支持分页和过滤的列表查询
	List(ctx context.Context, opts DeviceCommandLogListOptions, page, pageSize int) ([]models.DeviceCommandLog, int64, error)
}

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

// NewGormDeviceCommandLogRepository 创建一个新的 DeviceCommandLogRepository GORM 实现
func NewGormDeviceCommandLogRepository(ctx context.Context, db *gorm.DB) DeviceCommandLogRepository {
	return &gormDeviceCommandLogRepository{ctx: ctx, db: db}
}

// Create 实现 DeviceCommandLogRepository 接口的 Create 方法
func (r *gormDeviceCommandLogRepository) Create(ctx context.Context, record *models.DeviceCommandLog) error {
	repoCtx := logs.AddFuncName(ctx, r.ctx, "Create")
	return r.db.WithContext(repoCtx).Create(record).Error
}

// FindByMessageID 实现 DeviceCommandLogRepository 接口的 FindByMessageID 方法
func (r *gormDeviceCommandLogRepository) FindByMessageID(ctx context.Context, messageID string) (*models.DeviceCommandLog, error) {
	repoCtx := logs.AddFuncName(ctx, r.ctx, "FindByMessageID")
	var record models.DeviceCommandLog
	if err := r.db.WithContext(repoCtx).Where("message_id = ?", messageID).First(&record).Error; err != nil {
		return nil, err
	}
	return &record, nil
}

// UpdateAcknowledgedAt 实现 DeviceCommandLogRepository 接口的 UpdateAcknowledgedAt 方法
func (r *gormDeviceCommandLogRepository) UpdateAcknowledgedAt(ctx context.Context, messageID string, acknowledgedAt time.Time, receivedSuccess bool) error {
	repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdateAcknowledgedAt")
	return r.db.WithContext(repoCtx).Model(&models.DeviceCommandLog{}).
		Where("message_id = ?", messageID).
		Updates(map[string]interface{}{
			"acknowledged_at":  acknowledgedAt,
			"received_success": receivedSuccess,
		}).Error
}

// List 实现了分页和过滤查询设备命令日志的功能
func (r *gormDeviceCommandLogRepository) List(ctx context.Context, opts DeviceCommandLogListOptions, page, pageSize int) ([]models.DeviceCommandLog, int64, error) {
	repoCtx := logs.AddFuncName(ctx, r.ctx, "List")
	// --- 校验分页参数 ---
	if page <= 0 || pageSize <= 0 {
		return nil, 0, ErrInvalidPagination
	}

	var results []models.DeviceCommandLog
	var total int64

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

	// --- 应用过滤条件 ---
	if opts.DeviceID != nil {
		query = query.Where("device_id = ?", *opts.DeviceID)
	}
	if opts.ReceivedSuccess != nil {
		query = query.Where("received_success = ?", *opts.ReceivedSuccess)
	}
	if opts.StartTime != nil {
		query = query.Where("sent_at >= ?", *opts.StartTime)
	}
	if opts.EndTime != nil {
		query = query.Where("sent_at <= ?", *opts.EndTime)
	}

	// --- 计算总数 ---
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// --- 应用排序条件 ---
	orderBy := "sent_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
}
