package postgres

import (
	"context"
	"fmt"
	"time"

	"gorm.io/gorm"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/internal/store"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
)

// OrderPackageInvalidateTaskStore 订单套餐失效任务数据访问层
type OrderPackageInvalidateTaskStore struct {
	db *gorm.DB
}

// NewOrderPackageInvalidateTaskStore 创建 OrderPackageInvalidateTaskStore 实例
func NewOrderPackageInvalidateTaskStore(db *gorm.DB) *OrderPackageInvalidateTaskStore {
	return &OrderPackageInvalidateTaskStore{db: db}
}

// Create 创建任务
func (s *OrderPackageInvalidateTaskStore) Create(ctx context.Context, task *model.OrderPackageInvalidateTask) error {
	return s.db.WithContext(ctx).Create(task).Error
}

// GetByID 按主键查询任务（Worker 直接查询，不过滤租户）
func (s *OrderPackageInvalidateTaskStore) GetByID(ctx context.Context, id uint) (*model.OrderPackageInvalidateTask, error) {
	var task model.OrderPackageInvalidateTask
	if err := s.db.WithContext(ctx).Where("id = ?", id).First(&task).Error; err != nil {
		return nil, err
	}
	return &task, nil
}

// List 分页查询任务列表
func (s *OrderPackageInvalidateTaskStore) List(ctx context.Context, opts *store.QueryOptions, filters map[string]interface{}) ([]*model.OrderPackageInvalidateTask, int64, error) {
	var tasks []*model.OrderPackageInvalidateTask
	var total int64

	query := s.db.WithContext(ctx).Model(&model.OrderPackageInvalidateTask{})

	if status, ok := filters["status"].(int); ok && status > 0 {
		query = query.Where("status = ?", status)
	}

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

	if opts == nil {
		opts = &store.QueryOptions{
			Page:     1,
			PageSize: constants.DefaultPageSize,
		}
	}
	offset := (opts.Page - 1) * opts.PageSize
	query = query.Offset(offset).Limit(opts.PageSize).Order("created_at DESC")

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

	return tasks, total, nil
}

// UpdateStatus 更新任务状态
func (s *OrderPackageInvalidateTaskStore) UpdateStatus(ctx context.Context, id uint, status int, errorMessage string) error {
	updates := map[string]interface{}{
		"status":     status,
		"updated_at": time.Now(),
	}
	if status == model.ImportTaskStatusProcessing {
		updates["started_at"] = time.Now()
	}
	if status == model.ImportTaskStatusCompleted || status == model.ImportTaskStatusFailed {
		updates["completed_at"] = time.Now()
	}
	if errorMessage != "" {
		updates["error_message"] = errorMessage
	}
	return s.db.WithContext(ctx).Model(&model.OrderPackageInvalidateTask{}).Where("id = ?", id).Updates(updates).Error
}

// UpdateResult 更新任务计数和失败明细
func (s *OrderPackageInvalidateTaskStore) UpdateResult(ctx context.Context, id uint, totalCount, successCount, failCount int, failedItems model.ImportResultItems) error {
	updates := map[string]interface{}{
		"total_count":   totalCount,
		"success_count": successCount,
		"fail_count":    failCount,
		"failed_items":  failedItems,
		"updated_at":    time.Now(),
	}
	return s.db.WithContext(ctx).Model(&model.OrderPackageInvalidateTask{}).Where("id = ?", id).Updates(updates).Error
}

// GenerateTaskNo 生成任务编号（OPINV-YYYYMMDD-XXXXXX）
func (s *OrderPackageInvalidateTaskStore) GenerateTaskNo() string {
	now := time.Now()
	dateStr := now.Format("20060102")
	seq := now.UnixNano() % 1000000
	return fmt.Sprintf("OPINV-%s-%06d", dateStr, seq)
}
