import { existsSync, readFileSync } from 'fs';
import { join } from 'path';

const prismaRoot = join(__dirname, '..', '..', 'prisma');
const migrationPath = join(
  prismaRoot,
  'migrations',
  '20260803000000_add_webhook_outbox',
  'migration.sql'
);

describe('webhook outbox migration', () => {
  it('creates the schema-backed outbox table with delivery constraints', () => {
    expect(existsSync(migrationPath)).toBe(true);

    const migration = readFileSync(migrationPath, 'utf8');

    expect(migration).toMatch(/CREATE TABLE\s+"webhook_outbox"\s*\(/i);
    expect(migration).toMatch(/"id"\s+UUID\s+NOT NULL\s*,/i);
    expect(migration).not.toMatch(/"id"\s+UUID[^,]*\bDEFAULT\b/i);
    expect(migration).toMatch(/"job_id"\s+UUID\s+NOT NULL/i);
    expect(migration).toMatch(/"event"\s+VARCHAR\(80\)\s+NOT NULL/i);
    expect(migration).toMatch(/"payload"\s+JSONB\s+NOT NULL/i);
    expect(migration).toMatch(/"status"\s+VARCHAR\(20\)\s+NOT NULL\s+DEFAULT\s+'pending'/i);
    expect(migration).toMatch(/"attempts"\s+INTEGER\s+NOT NULL\s+DEFAULT\s+0/i);
    expect(migration).toMatch(/"last_error"\s+TEXT/i);
    expect(migration).toMatch(/"claimed_at"\s+TIMESTAMP\(3\)/i);
    expect(migration).toMatch(/"delivered_at"\s+TIMESTAMP\(3\)/i);
    expect(migration).toMatch(/"created_at"\s+TIMESTAMP\(3\)\s+NOT NULL\s+DEFAULT\s+CURRENT_TIMESTAMP/i);
    expect(migration).toMatch(/CONSTRAINT\s+"webhook_outbox_pkey"\s+PRIMARY KEY\s+\("id"\)/i);
    expect(migration).toMatch(/CREATE UNIQUE INDEX\s+"webhook_outbox_job_id_event_key"\s+ON\s+"webhook_outbox"\s*\(\s*"job_id"\s*,\s*"event"\s*\)/i);
    expect(migration).toMatch(/CREATE INDEX\s+"webhook_outbox_status_created_at_idx"\s+ON\s+"webhook_outbox"\s*\(\s*"status"\s*,\s*"created_at"\s*\)/i);
    expect(migration).toMatch(/ALTER TABLE\s+"webhook_outbox"\s+ADD CONSTRAINT\s+"webhook_outbox_job_id_fkey"\s+FOREIGN KEY\s+\("job_id"\)\s+REFERENCES\s+"translation_jobs"\s*\(\s*"id"\s*\)\s+ON DELETE CASCADE\s+ON UPDATE CASCADE/i);
  });
});
