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/break/junhong_cmp_fiber/pkg/middleware"
	"github.com/redis/go-redis/v9"
	"gorm.io/gorm"
)

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

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

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

func (s *IotCardImportTaskStore) GetByID(ctx context.Context, id uint) (*model.IotCardImportTask, error) {
	var task model.IotCardImportTask
	query := s.db.WithContext(ctx).Where("id = ?", id)
	// 应用数据权限过滤
	query = middleware.ApplyShopFilter(ctx, query)
	if err := query.First(&task).Error; err != nil {
		return nil, err
	}
	return &task, nil
}

func (s *IotCardImportTaskStore) GetByTaskNo(ctx context.Context, taskNo string) (*model.IotCardImportTask, error) {
	var task model.IotCardImportTask
	query := s.db.WithContext(ctx).Where("task_no = ?", taskNo)
	// 应用数据权限过滤
	query = middleware.ApplyShopFilter(ctx, query)
	if err := query.First(&task).Error; err != nil {
		return nil, err
	}
	return &task, nil
}

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

func (s *IotCardImportTaskStore) 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.IotCardImportTask{}).Where("id = ?", id).Updates(updates).Error
}

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

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

func (s *IotCardImportTaskStore) List(ctx context.Context, opts *store.QueryOptions, filters map[string]interface{}) ([]*model.IotCardImportTask, int64, error) {
	var tasks []*model.IotCardImportTask
	var total int64

	query := s.db.WithContext(ctx).Model(&model.IotCardImportTask{})
	// 应用数据权限过滤
	query = middleware.ApplyShopFilter(ctx, query)

	if status, ok := filters["status"].(int); ok && status > 0 {
		query = query.Where("status = ?", status)
	}
	if carrierID, ok := filters["carrier_id"].(uint); ok && carrierID > 0 {
		query = query.Where("carrier_id = ?", carrierID)
	}
	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 *IotCardImportTaskStore) UpdateCardList(ctx context.Context, id uint, cards model.CardListJSON, totalCount int) error {
	updates := map[string]interface{}{
		"card_list":   cards,
		"total_count": totalCount,
		"updated_at":  time.Now(),
	}
	return s.db.WithContext(ctx).Model(&model.IotCardImportTask{}).Where("id = ?", id).Updates(updates).Error
}

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