import { describe, expect, it } from 'vitest';

import {
  createBusySearchExecutorStatus,
  createIdleSearchExecutorStatus,
} from './search-executor-state.ts';

describe('search-executor-state', () => {
  const baseTask = {
    id: 'task-001',
    batch_id: 'CG-001',
    account_id: 'account-001',
    pipeline_config: {
      keywordSearchEnabled: true,
      imageSearchEnabled: true,
      keywordCombinations: [],
      includeAiKeyword: true,
    },
    contact_limit: 10,
    headless: false,
    status: 'processing' as const,
    total_rows: 12,
    processed_rows: 5,
    completed_rows: 4,
    failed_rows: 1,
    stopped_rows: 0,
    current_material_id: 'material-005',
    current_item: '正在处理第 6 行',
    error_message: '',
    errors: [],
    result: {},
    created_at: '2026-04-21T08:00:00.000Z',
    updated_at: '2026-04-21T08:05:00.000Z',
    started_at: '2026-04-21T08:00:00.000Z',
    paused_at: null,
    finished_at: null,
  };

  it('creates an idle executor payload', () => {
    expect(createIdleSearchExecutorStatus()).toEqual({
      state: 'idle',
      canStart: true,
      canManage: false,
      status: 'idle',
      message: '搜索执行器空闲',
      task: null,
    });
  });

  it('includes task details when the current user can manage the blocking task', () => {
    const payload = createBusySearchExecutorStatus(baseTask, true);

    expect(payload).toMatchObject({
      state: 'busy',
      canStart: false,
      canManage: true,
      status: 'processing',
      task: {
        taskId: 'task-001',
        batchId: 'CG-001',
        processedRows: 5,
      },
    });
    expect(payload.message).toContain('请继续或停止后再试');
  });

  it('redacts task details when the blocking task is not manageable', () => {
    const payload = createBusySearchExecutorStatus(baseTask, false);

    expect(payload).toMatchObject({
      state: 'busy',
      canStart: false,
      canManage: false,
      status: 'processing',
      task: null,
    });
    expect(payload.message).toContain('当前有其他搜索任务正在占用执行器');
  });

  it('treats waiting_for_manual as a blocking executor status', () => {
    const payload = createBusySearchExecutorStatus({
      ...baseTask,
      status: 'waiting_for_manual' as const,
      current_item: '等待人工处理验证码',
    }, true);

    expect(payload).toMatchObject({
      state: 'busy',
      canStart: false,
      canManage: true,
      status: 'waiting_for_manual',
      task: {
        currentItem: '等待人工处理验证码',
      },
    });
  });
});