import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import {
  PlaywrightAutomationAdapter,
  FixtureServer,
} from 'core/automation/infrastructure//automation';
import { StepId } from 'apps/companion/main/automation/domain/value-objects/StepId';
import { PinoLogAdapter } from 'core/automation/infrastructure//logging/PinoLogAdapter';
import { executeStepWithAutoNavigationGuard } from '../support/AutoNavGuard';

describe('Hosted validator guards (fixture-backed, real stack)', () => {
  let server: FixtureServer;
  let adapter: PlaywrightAutomationAdapter;
  let baseUrl: string;

  beforeAll(async () => {
    server = new FixtureServer();
    const info = await server.start();
    baseUrl = info.url;

    const logger = new PinoLogAdapter();

    adapter = new PlaywrightAutomationAdapter(
      {
        headless: true,
        timeout: 15_000,
        baseUrl,
        mode: 'real',
        userDataDir: '',
      },
        logger,
    );

    const result = await adapter.connect(false);
    expect(result.success).toBe(true);
    expect(adapter.isConnected()).toBe(true);
  }, 120_000);

  afterAll(async () => {
    if (adapter) {
      await adapter.disconnect();
    }
    if (server) {
      await server.stop();
    }
  });

  it(
    'runs a short hosted sequence (3 → 4 → 5) with autonav and no validator failures',
    async () => {
      await adapter.navigateToPage(server.getFixtureUrl(3));
      const step3Result = await executeStepWithAutoNavigationGuard(adapter, 3, {
        sessionName: 'Validator happy-path session',
        password: 'validator',
        description: 'Validator autonav slice',
      });
      expect(step3Result.success).toBe(true);

      await adapter.navigateToPage(server.getFixtureUrl(4));
      const step4Result = await executeStepWithAutoNavigationGuard(adapter, 4, {
        region: 'US',
        startNow: true,
      });
      expect(step4Result.success).toBe(true);

      await adapter.navigateToPage(server.getFixtureUrl(5));
      const step5Result = await executeStepWithAutoNavigationGuard(adapter, 5, {});
      expect(step5Result.success).toBe(true);
    },
    120_000,
  );

  it(
    'fails clearly when executing a mismatched step on the wrong page (validator wiring)',
    async () => {
      await adapter.navigateToPage(server.getFixtureUrl(8));
      const stepId = StepId.create(11);

      await expect(
        adapter.executeStep(stepId, {
          trackSearch: 'Spa',
          __skipFixtureNavigation: true,
        }),
      ).rejects.toThrow(/Step 11 FAILED validation|validation error/i);
    },
    120_000,
  );
});