import { readFile } from 'node:fs/promises';
import path from 'node:path';

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

const SERVER_PATH = path.join(import.meta.dirname, 'server.ts');
const SEARCH_PLAN_PATH = path.join(import.meta.dirname, '..', 'playwright', 'search-plan.js');

async function readRunSearchTaskBody() {
  const source = await readFile(SERVER_PATH, 'utf8');
  const start = source.indexOf('async function runSearchTask');
  const end = source.indexOf('function readSearchTaskId', start);

  expect(start).toBeGreaterThanOrEqual(0);
  expect(end).toBeGreaterThan(start);

  return source.slice(start, end);
}

describe('search task login handoff', () => {
  it('lets the search child own 1688 login warmup instead of spawning the standalone login script first', async () => {
    const runSearchTaskBody = await readRunSearchTaskBody();

    expect(runSearchTaskBody).not.toContain('LOGIN_1688_SCRIPT');
    expect(runSearchTaskBody).not.toContain('1688 账户登录');
    expect(runSearchTaskBody).toContain('ROW_PIPELINE_SYNC_SCRIPT');
    expect(runSearchTaskBody).toContain('正在检查登录态并准备搜索');
  });

  it('serializes same-account search execution and syncs login profile back to the account profile', async () => {
    const source = await readFile(SERVER_PATH, 'utf8');
    const runSearchTaskBody = await readRunSearchTaskBody();

    expect(source).toContain('from "./search-account-lock.ts"');
    expect(source).toContain('from "./search-profile-workspace.ts"');
    expect(runSearchTaskBody).toContain('withSearchAccountExecutionLock(account.id');
    expect(runSearchTaskBody).toContain('prepareSearchTaskRuntimeProfile');
    expect(runSearchTaskBody).toContain('syncSearchTaskRuntimeProfileToAccount');
    expect(runSearchTaskBody).toContain('等待 1688 账户空闲');
  });

  it('syncs the login profile immediately after the search child confirms login warmup', async () => {
    const source = await readFile(SERVER_PATH, 'utf8');
    const searchPlanSource = await readFile(SEARCH_PLAN_PATH, 'utf8');

    expect(searchPlanSource).toContain('login_session_ready');
    expect(source).toContain('type !== "login_session_ready"');

    const applyStart = source.indexOf('async function applySearchChildEvent');
    const applyEnd = source.indexOf('async function runManagedSearchChild', applyStart);
    expect(applyStart).toBeGreaterThanOrEqual(0);
    expect(applyEnd).toBeGreaterThan(applyStart);

    const applyBody = source.slice(applyStart, applyEnd);
    const loginEventIndex = applyBody.indexOf('event.type === "login_session_ready"');
    const syncIndex = applyBody.indexOf('syncSearchTaskRuntimeProfileToAccount', loginEventIndex);

    expect(loginEventIndex).toBeGreaterThanOrEqual(0);
    expect(syncIndex).toBeGreaterThan(loginEventIndex);
  });
});
