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

const migrationPath = join(
  process.cwd(),
  'prisma',
  'migrations',
  '20260708000000_v27_enterprise_collab_governance',
  'migration.sql',
);

function readMigrationSql() {
  if (!existsSync(migrationPath)) {
    throw new Error(`Missing V2.7 migration: ${migrationPath}`);
  }
  return readFileSync(migrationPath, 'utf8');
}

describe('V2.7 enterprise collaboration schema migration', () => {
  it('creates notification records for assignment, mention, risk alert, and overdue events', () => {
    const sql = readMigrationSql();

    expect(sql).toMatch(/CREATE TABLE "notifications"/);
    expect(sql).toMatch(/"type" TEXT NOT NULL/);
    expect(sql).toMatch(/"recipient_id" TEXT NOT NULL/);
    expect(sql).toMatch(/"read_at" TIMESTAMP\(3\)/);
    expect(sql).toMatch(/CREATE INDEX "notifications_recipient_read_created_idx"/);
  });

  it('creates polymorphic comments with mention metadata', () => {
    const sql = readMigrationSql();

    expect(sql).toMatch(/CREATE TABLE "comments"/);
    expect(sql).toMatch(/"entity_type" TEXT NOT NULL/);
    expect(sql).toMatch(/"entity_id" TEXT NOT NULL/);
    expect(sql).toMatch(/"mentioned_member_ids" JSONB NOT NULL DEFAULT '\[\]'/);
    expect(sql).toMatch(/CREATE INDEX "comments_entity_created_idx"/);
  });

  it('adds audit logs and governance dictionaries with soft-delete support', () => {
    const sql = readMigrationSql();

    expect(sql).toMatch(/CREATE TABLE "audit_logs"/);
    expect(sql).toMatch(/"before" JSONB NOT NULL DEFAULT '\{\}'/);
    expect(sql).toMatch(/"after" JSONB NOT NULL DEFAULT '\{\}'/);
    expect(sql).toMatch(/CREATE TABLE "governance_dictionaries"/);
    expect(sql).toMatch(/"deleted_at" TIMESTAMP\(3\)/);
    expect(sql).toMatch(/CONSTRAINT "governance_dictionaries_scope_kind_name_key" UNIQUE/);
  });
});
