/**
 * Pipeline transition integration tests.
 *
 * Verifies:
 *  - An interest can advance through all 8 pipeline stages
 *  - Each transition is logged in audit_logs with action='update'
 *  - Backward transitions are permitted
 *  - Milestone auto-population (BR-133)
 *  - Socket event name is 'interest:stageChanged'
 *
 * Skips gracefully when TEST_DATABASE_URL is not reachable.
 */
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';

import { PIPELINE_STAGES } from '@/lib/constants';
import {
  makeAuditMeta,
  makeCreateClientInput,
  makeCreateInterestInput,
} from '../helpers/factories';

// External side-effects mocked so the test stays self-contained.
vi.mock('@/lib/socket/server', () => ({ emitToRoom: vi.fn() }));
vi.mock('@/lib/queue', () => ({
  getQueue: () => ({ add: vi.fn().mockResolvedValue(undefined) }),
}));

const TEST_DB_URL =
  process.env.TEST_DATABASE_URL || 'postgresql://test:test@localhost:5433/portnimara_test';

// ─── DB Availability Check ────────────────────────────────────────────────────

let dbAvailable = false;

beforeAll(async () => {
  try {
    const postgres = (await import('postgres')).default;
    const sql = postgres(TEST_DB_URL, { max: 1, idle_timeout: 3, connect_timeout: 3 });
    await sql`SELECT 1`;
    await sql.end();
    dbAvailable = true;
  } catch {
    console.warn('[pipeline-transitions] Test database not available - skipping integration tests');
  }
});

function itDb(name: string, fn: () => Promise<void>) {
  it(name, async () => {
    if (!dbAvailable) return;
    await fn();
  });
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

async function seedPort(): Promise<string> {
  const postgres = (await import('postgres')).default;
  const sql = postgres(TEST_DB_URL, { max: 1 });
  const portId = crypto.randomUUID();
  await sql`
    INSERT INTO ports (id, name, slug, country, currency, timezone)
    VALUES (${portId}, 'Pipeline Test Port', ${'pipeline-' + portId.slice(0, 8)}, 'AU', 'AUD', 'UTC')
  `;
  await sql.end();
  return portId;
}

async function cleanupPort(portId: string): Promise<void> {
  const postgres = (await import('postgres')).default;
  const sql = postgres(TEST_DB_URL, { max: 1 });
  await sql`DELETE FROM ports WHERE id = ${portId}`;
  await sql.end();
}

async function getLatestAuditLog(
  portId: string,
  entityId: string,
): Promise<Record<string, unknown> | null> {
  const postgres = (await import('postgres')).default;
  const sql = postgres(TEST_DB_URL, { max: 1 });
  const rows = await sql<Record<string, unknown>[]>`
    SELECT * FROM audit_logs
    WHERE port_id = ${portId} AND entity_id = ${entityId}
    ORDER BY created_at DESC
    LIMIT 1
  `;
  await sql.end();
  return rows[0] ?? null;
}

// ─── Tests ────────────────────────────────────────────────────────────────────

describe('Pipeline Transitions', () => {
  let portId: string;
  let interestId: string;

  beforeAll(async () => {
    if (!dbAvailable) return;

    portId = await seedPort();

    const { createClient } = await import('@/lib/services/clients.service');
    const meta = makeAuditMeta({ portId });

    const client = await createClient(
      portId,
      makeCreateClientInput({ fullName: 'Pipeline Test Client' }),
      meta,
    );

    const { createInterest } = await import('@/lib/services/interests.service');
    const interest = await createInterest(
      portId,
      makeCreateInterestInput({ clientId: client.id }),
      meta,
    );
    interestId = interest.id;
  });

  afterAll(async () => {
    if (!dbAvailable) return;
    await cleanupPort(portId);
  });

  itDb('advances through all 7 pipeline stages sequentially', async () => {
    const { changeInterestStage, getInterestById } =
      await import('@/lib/services/interests.service');
    const meta = makeAuditMeta({ portId });

    for (const stage of PIPELINE_STAGES) {
      // Skip-ahead jumps are blocked unless override=true; the test runs
      // through each stage so we override consistently.
      await changeInterestStage(
        interestId,
        portId,
        { pipelineStage: stage, override: true, reason: 'sequential walk for test' },
        meta,
      );

      const updated = await getInterestById(interestId, portId);
      expect(updated.pipelineStage).toBe(stage);
    }
  });

  itDb('each stage transition creates an audit log entry with action=update', async () => {
    const { changeInterestStage } = await import('@/lib/services/interests.service');
    const meta = makeAuditMeta({ portId });

    await changeInterestStage(interestId, portId, { pipelineStage: 'enquiry' }, meta);

    // Allow async audit log to flush
    await new Promise((r) => setTimeout(r, 100));

    const log = await getLatestAuditLog(portId, interestId);
    expect(log).not.toBeNull();
    expect(log!.action).toBe('update');
    expect(log!.entity_type).toBe('interest');

    const newValue = log!.new_value as Record<string, unknown>;
    expect(newValue.pipelineStage).toBe('enquiry');
  });

  itDb('backward transition: contract → enquiry is permitted with override', async () => {
    const { changeInterestStage, getInterestById } =
      await import('@/lib/services/interests.service');
    const meta = makeAuditMeta({ portId });

    await changeInterestStage(
      interestId,
      portId,
      { pipelineStage: 'contract', override: true, reason: 'jump for backward test' },
      meta,
    );
    await changeInterestStage(
      interestId,
      portId,
      { pipelineStage: 'enquiry', override: true, reason: 'backward rewind for test' },
      meta,
    );

    const updated = await getInterestById(interestId, portId);
    expect(updated.pipelineStage).toBe('enquiry');
  });

  itDb('BR-133: advancing to eoi auto-populates dateEoiSent', async () => {
    const { changeInterestStage, getInterestById } =
      await import('@/lib/services/interests.service');
    const meta = makeAuditMeta({ portId });

    await changeInterestStage(
      interestId,
      portId,
      { pipelineStage: 'eoi', override: true, reason: 'milestone backfill test' },
      meta,
    );

    const updated = await getInterestById(interestId, portId);
    expect(updated.dateEoiSent).not.toBeNull();
  });

  itDb('BR-133: advancing to contract auto-populates dateContractSent', async () => {
    const { changeInterestStage, getInterestById } =
      await import('@/lib/services/interests.service');
    const meta = makeAuditMeta({ portId });

    await changeInterestStage(
      interestId,
      portId,
      { pipelineStage: 'contract', override: true, reason: 'milestone backfill test' },
      meta,
    );

    const updated = await getInterestById(interestId, portId);
    expect(updated.dateContractSent).not.toBeNull();
  });

  itDb('BR-133: advancing to deposit_paid auto-populates dateDepositReceived', async () => {
    const { changeInterestStage, getInterestById } =
      await import('@/lib/services/interests.service');
    const meta = makeAuditMeta({ portId });

    await changeInterestStage(
      interestId,
      portId,
      { pipelineStage: 'deposit_paid', override: true, reason: 'milestone backfill test' },
      meta,
    );

    const updated = await getInterestById(interestId, portId);
    expect(updated.dateDepositReceived).not.toBeNull();
  });

  itDb('stage change emits interest:stageChanged socket event', async () => {
    const { emitToRoom } = await import('@/lib/socket/server');
    const { changeInterestStage } = await import('@/lib/services/interests.service');
    const meta = makeAuditMeta({ portId });

    vi.clearAllMocks();

    await changeInterestStage(interestId, portId, { pipelineStage: 'qualified' }, meta);

    expect(emitToRoom).toHaveBeenCalledWith(
      `port:${portId}`,
      'interest:stageChanged',
      expect.objectContaining({ interestId, newStage: 'qualified' }),
    );
  });
});
