import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Audit trail for contract document edits. The document stays editable through
 * the whole approval chain (each approver may edit on their turn), so the
 * contract itself only ever holds the current snapshot — this table records who
 * changed which article, and when.
 */
export class CreateContractDocumentRevisions2420000000000
  implements MigrationInterface
{
  name = 'CreateContractDocumentRevisions2420000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.contract_document_revisions (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        created_at timestamptz NOT NULL DEFAULT now(),
        updated_at timestamptz NOT NULL DEFAULT now(),
        deleted_at timestamptz,
        contract_id uuid NOT NULL REFERENCES freight.contracts(id) ON DELETE CASCADE,
        actor_id uuid,
        actor_role varchar(64),
        step_id uuid,
        summary varchar(255),
        changes jsonb NOT NULL DEFAULT '[]'::jsonb
      );
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_contract_document_revisions_contract
        ON freight.contract_document_revisions (contract_id, created_at DESC);
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `DROP TABLE IF EXISTS freight.contract_document_revisions;`,
    );
  }
}
