import type { SearchTaskRow, SearchTaskStatus } from "../core/types.ts";

export type SearchExecutorBusyStatus = Extract<SearchTaskStatus, "pending" | "processing" | "waiting_for_manual" | "pausing" | "paused" | "stopping">;

export interface SearchExecutorTaskSummary {
  taskId: string;
  status: SearchExecutorBusyStatus;
  batchId: string;
  accountId: string;
  totalRows: number;
  processedRows: number;
  completedRows: number;
  failedRows: number;
  stoppedRows: number;
  currentItem: string;
  startedAt: string | null;
  pausedAt: string | null;
  finishedAt: string | null;
}

export interface SearchExecutorStatusPayload {
  state: "idle" | "busy";
  canStart: boolean;
  canManage: boolean;
  status: "idle" | SearchExecutorBusyStatus;
  message: string;
  task: SearchExecutorTaskSummary | null;
}

export const SEARCH_EXECUTOR_BUSY_ERROR_CODE = "SEARCH_EXECUTOR_BUSY";
export const MANAGEABLE_SEARCH_EXECUTOR_BUSY_MESSAGE = "已有搜索任务正在占用执行器，请继续或停止后再试";
export const BLOCKED_SEARCH_EXECUTOR_BUSY_MESSAGE = "当前有其他搜索任务正在占用执行器，请稍后再试";
export const IDLE_SEARCH_EXECUTOR_MESSAGE = "搜索执行器空闲";

function formatBusyMessage(baseMessage: string, status: SearchExecutorBusyStatus) {
  return `${baseMessage}（${status}）`;
}

export function summarizeSearchExecutorTask(task: SearchTaskRow): SearchExecutorTaskSummary {
  return {
    taskId: task.id ?? "",
    status: task.status as SearchExecutorBusyStatus,
    batchId: task.batch_id,
    accountId: task.account_id,
    totalRows: task.total_rows,
    processedRows: task.processed_rows,
    completedRows: task.completed_rows,
    failedRows: task.failed_rows,
    stoppedRows: task.stopped_rows,
    currentItem: task.current_item,
    startedAt: task.started_at ?? null,
    pausedAt: task.paused_at ?? null,
    finishedAt: task.finished_at ?? null,
  };
}

export function createIdleSearchExecutorStatus(
  message: string = IDLE_SEARCH_EXECUTOR_MESSAGE,
): SearchExecutorStatusPayload {
  return {
    state: "idle",
    canStart: true,
    canManage: false,
    status: "idle",
    message,
    task: null,
  };
}

export function createBusySearchExecutorStatus(
  task: SearchTaskRow,
  canManage: boolean,
): SearchExecutorStatusPayload {
  const status = task.status as SearchExecutorBusyStatus;
  const baseMessage = canManage
    ? MANAGEABLE_SEARCH_EXECUTOR_BUSY_MESSAGE
    : BLOCKED_SEARCH_EXECUTOR_BUSY_MESSAGE;

  return {
    state: "busy",
    canStart: false,
    canManage,
    status,
    message: formatBusyMessage(baseMessage, status),
    task: canManage ? summarizeSearchExecutorTask(task) : null,
  };
}