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');

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 账户空闲');
  });
});
