import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Keep every version of a stored document.
 *
 * Replacing a file used to DELETE the previous row outright, so a staff
 * correction erased the customer's original upload with no trail. Superseded
 * versions are now soft-deleted (already excluded from every read by TypeORM's
 * soft-delete filter) and stamped with who replaced them and why, which is what
 * the document's version history reads back.
 */
export class AddFileVersionHistory2940000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.files
        ADD COLUMN IF NOT EXISTS replaced_by_user_id uuid NULL,
        ADD COLUMN IF NOT EXISTS replace_reason text NULL
    `);
    // History reads walk one document's versions, deleted rows included.
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_files_version_history"
        ON freight.files (resource, resource_id, code, created_at DESC)
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS freight."IDX_files_version_history"`);
    await queryRunner.query(`
      ALTER TABLE freight.files
        DROP COLUMN IF EXISTS replaced_by_user_id,
        DROP COLUMN IF EXISTS replace_reason
    `);
  }
}
