package postgres

import (
	"context"
	"fmt"
	"time"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/internal/store"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/redis/go-redis/v9"
	"gorm.io/gorm"
)

type DeviceImportTaskStore struct {
	db    *gorm.DB
	redis *redis.Client
}

func NewDeviceImportTaskStore(db *gorm.DB, redis *redis.Client) *DeviceImportTaskStore {
	return &DeviceImportTaskStore{
		db:    db,
		redis: redis,
	}
}

func (s *DeviceImportTaskStore) Create(ctx context.Context, task *model.DeviceImportTask) error {
	return s.db.WithContext(ctx).Create(task).Error
}

func (s *DeviceImportTaskStore) GetByID(ctx context.Context, id uint) (*model.DeviceImportTask, error) {
	var task model.DeviceImportTask
	if err := s.db.WithContext(ctx).First(&task, id).Error; err != nil {
		return nil, err
	}
	return &task, nil
}

func (s *DeviceImportTaskStore) GetByTaskNo(ctx context.Context, taskNo string) (*model.DeviceImportTask, error) {
	var task model.DeviceImportTask
	if err := s.db.WithContext(ctx).Where("task_no = ?", taskNo).First(&task).Error; err != nil {
		return nil, err
	}
	return &task, nil
}

func (s *DeviceImportTaskStore) Update(ctx context.Context, task *model.DeviceImportTask) error {
	return s.db.WithContext(ctx).Save(task).Error
}

func (s *DeviceImportTaskStore) UpdateStatus(ctx context.Context, id uint, status int, errorMessage string) error {
	updates := map[string]any{
		"status":     status,
		"updated_at": time.Now(),
	}
	if status == model.ImportTaskStatusProcessing {
		now := time.Now()
		updates["started_at"] = &now
	}
	if status == model.ImportTaskStatusCompleted || status == model.ImportTaskStatusFailed {
		now := time.Now()
		updates["completed_at"] = &now
	}
	if errorMessage != "" {
		updates["error_message"] = errorMessage
	}
	return s.db.WithContext(ctx).Model(&model.DeviceImportTask{}).Where("id = ?", id).Updates(updates).Error
}

// UpdateProgress 实时更新导入进度计数（不更新详情列表，用于批量处理中间状态）
func (s *DeviceImportTaskStore) UpdateProgress(ctx context.Context, id uint, successCount, skipCount, failCount int) error {
	return s.db.WithContext(ctx).Model(&model.DeviceImportTask{}).Where("id = ?", id).Updates(map[string]any{
		"success_count": successCount,
		"skip_count":    skipCount,
		"fail_count":    failCount,
		"updated_at":    time.Now(),
	}).Error
}

func (s *DeviceImportTaskStore) UpdateResult(ctx context.Context, id uint, totalCount, successCount, skipCount, failCount, warningCount int, skippedItems, failedItems, warningItems model.ImportResultItems) error {
	updates := map[string]any{
		"total_count":   totalCount,
		"success_count": successCount,
		"skip_count":    skipCount,
		"fail_count":    failCount,
		"warning_count": warningCount,
		"skipped_items": skippedItems,
		"failed_items":  failedItems,
		"warning_items": warningItems,
		"updated_at":    time.Now(),
	}
	return s.db.WithContext(ctx).Model(&model.DeviceImportTask{}).Where("id = ?", id).Updates(updates).Error
}

func (s *DeviceImportTaskStore) List(ctx context.Context, opts *store.QueryOptions, filters map[string]any) ([]*model.DeviceImportTask, int64, error) {
	var tasks []*model.DeviceImportTask
	var total int64

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

	if status, ok := filters["status"].(int); ok && status > 0 {
		query = query.Where("status = ?", status)
	}
	if operationType, ok := filters["operation_type"].(string); ok && operationType != "" {
		query = query.Where("operation_type = ?", operationType)
	}
	if batchNo, ok := filters["batch_no"].(string); ok && batchNo != "" {
		query = query.Where("batch_no LIKE ?", "%"+batchNo+"%")
	}
	if startTime, ok := filters["start_time"].(time.Time); ok && !startTime.IsZero() {
		query = query.Where("created_at >= ?", startTime)
	}
	if endTime, ok := filters["end_time"].(time.Time); ok && !endTime.IsZero() {
		query = query.Where("created_at <= ?", endTime)
	}

	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)

	if opts.OrderBy != "" {
		query = query.Order(opts.OrderBy)
	} else {
		query = query.Order("created_at DESC")
	}

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

	return tasks, total, nil
}

func (s *DeviceImportTaskStore) GenerateTaskNo(ctx context.Context) string {
	now := time.Now()
	dateStr := now.Format("20060102")
	seq := now.UnixNano() % 1000000
	return fmt.Sprintf("DEV-IMP-%s-%06d", dateStr, seq)
}
