package postgres

import (
	"context"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"gorm.io/gorm"
)

// AssetOperationLogStore 资产操作日志存储层。
type AssetOperationLogStore struct {
	db *gorm.DB
}

// NewAssetOperationLogStore 创建资产操作日志存储实例。
func NewAssetOperationLogStore(db *gorm.DB) *AssetOperationLogStore {
	return &AssetOperationLogStore{db: db}
}

// Create 创建资产操作日志记录。
func (s *AssetOperationLogStore) Create(ctx context.Context, log *model.AssetOperationLog) error {
	return s.db.WithContext(ctx).Create(log).Error
}

// ListByAssetPaged 按资产分页查询日志。
func (s *AssetOperationLogStore) ListByAssetPaged(
	ctx context.Context,
	assetType string,
	assetID uint,
	page int,
	pageSize int,
	operationType string,
	resultStatus string,
) ([]*model.AssetOperationLog, int64, error) {
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 {
		pageSize = 20
	}

	query := s.db.WithContext(ctx).Model(&model.AssetOperationLog{}).
		Where("asset_type = ? AND asset_id = ?", assetType, assetID)

	if operationType != "" {
		query = query.Where("operation_type = ?", operationType)
	}
	if resultStatus != "" {
		query = query.Where("result_status = ?", resultStatus)
	}

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

	offset := (page - 1) * pageSize
	var logs []*model.AssetOperationLog
	if err := query.Order("created_at DESC, id DESC").Offset(offset).Limit(pageSize).Find(&logs).Error; err != nil {
		return nil, 0, err
	}

	return logs, total, nil
}

// ListByAsset 按资产查询日志。
func (s *AssetOperationLogStore) ListByAsset(ctx context.Context, assetType string, assetID uint, limit int) ([]*model.AssetOperationLog, error) {
	if limit <= 0 {
		limit = 20
	}
	var logs []*model.AssetOperationLog
	err := s.db.WithContext(ctx).
		Where("asset_type = ? AND asset_id = ?", assetType, assetID).
		Order("created_at DESC").
		Limit(limit).
		Find(&logs).Error
	return logs, err
}

// ListByOperator 按操作人查询日志。
func (s *AssetOperationLogStore) ListByOperator(ctx context.Context, operatorID uint, limit int) ([]*model.AssetOperationLog, error) {
	if limit <= 0 {
		limit = 20
	}
	var logs []*model.AssetOperationLog
	err := s.db.WithContext(ctx).
		Where("operator_id = ?", operatorID).
		Order("created_at DESC").
		Limit(limit).
		Find(&logs).Error
	return logs, err
}

// ListByOperationType 按操作类型查询日志。
func (s *AssetOperationLogStore) ListByOperationType(ctx context.Context, operationType string, limit int) ([]*model.AssetOperationLog, error) {
	if limit <= 0 {
		limit = 20
	}
	var logs []*model.AssetOperationLog
	err := s.db.WithContext(ctx).
		Where("operation_type = ?", operationType).
		Order("created_at DESC").
		Limit(limit).
		Find(&logs).Error
	return logs, err
}
