// ============================================================
// infrastructure/storage/task-store.ts — 任务记录本地存储
//
// 职责：
//   - 插入/更新/查询任务记录
//   - 批量同步 API 数据
//   - 按用户 + 状态/模型筛选
// ============================================================

import { execute, queryAll, queryOne } from '../core/db-core';
import { getCurrentUserId } from '../services/user-scope';
import type { TaskRecordEntry, TaskQueryFilter } from '../core/types';
import type { TaskInfoItemResponseBody } from '@/modules/home/controllers/task-api';
import { logger } from '@/shared/utils/bus';

// ---------- 序列化 ----------

function taskToRow(task: TaskInfoItemResponseBody): TaskRecordEntry {
  return {
    id: task.id,
    user_id: getCurrentUserId(),
    model_id: task.model_id,
    status: task.status,
    data_json: JSON.stringify(task),
    created_at: typeof task.created_at === 'string' ? Date.parse(task.created_at) : Date.now(),
    updated_at: Date.now(),
  };
}

export function rowToTask(row: TaskRecordEntry): TaskInfoItemResponseBody {
  try {
    return JSON.parse(row.data_json) as TaskInfoItemResponseBody;
  } catch {
    return { id: row.id, model_id: row.model_id, status: row.status, created_at: new Date(row.created_at).toISOString() } as unknown as TaskInfoItemResponseBody;
  }
}

// ---------- API ----------

export function upsertTask(task: TaskInfoItemResponseBody): void {
  const r = taskToRow(task);
  execute(
    `INSERT OR REPLACE INTO task_records (id, user_id, model_id, status, data_json, created_at, updated_at)
     VALUES (?, ?, ?, ?, ?, ?, ?)`,
    [r.id, r.user_id, r.model_id, r.status, r.data_json, r.created_at, r.updated_at],
  );
}

export function syncTasks(tasks: TaskInfoItemResponseBody[]): number {
  let n = 0;
  for (const t of tasks) {
    try { upsertTask(t); n++; } catch { /* skip */ }
  }
  logger.debug('storage', `任务同步：${n}/${tasks.length}`);
  return n;
}

export function getTasks(filter: TaskQueryFilter = {}): TaskRecordEntry[] {
  const uid = getCurrentUserId();
  if (filter.status) {
    return queryAll<TaskRecordEntry>(
      `SELECT * FROM task_records WHERE user_id = ? AND status = ? ORDER BY created_at DESC LIMIT ?`,
      [uid, filter.status, filter.limit || 100],
    );
  }
  if (filter.model_id) {
    return queryAll<TaskRecordEntry>(
      `SELECT * FROM task_records WHERE user_id = ? AND model_id = ? ORDER BY created_at DESC LIMIT ?`,
      [uid, filter.model_id, filter.limit || 100],
    );
  }
  return queryAll<TaskRecordEntry>(
    `SELECT * FROM task_records WHERE user_id = ? ORDER BY created_at DESC LIMIT ?`,
    [uid, filter.limit || 100],
  );
}

export function getTaskById(taskId: string): TaskRecordEntry | null {
  return queryOne<TaskRecordEntry>(`SELECT * FROM task_records WHERE id = ?`, [taskId]);
}

export function deleteTask(taskId: string): void {
  execute(`DELETE FROM task_records WHERE id = ?`, [taskId]);
}

export function getTaskCount(userId?: string): number {
  const row = queryOne<{ cnt: number }>(
    `SELECT COUNT(*) as cnt FROM task_records WHERE user_id = ?`,
    [userId || getCurrentUserId()],
  );
  return row?.cnt ?? 0;
}

export function clearUserTasks(): void {
  const uid = getCurrentUserId();
  execute(`DELETE FROM task_records WHERE user_id = ?`, [uid]);
}
