import { MigrationInterface, QueryRunner, Table, TableIndex } from 'typeorm';

/**
 * Staging table for customer profile edits that require backoffice review. An
 * already-approved company's settings edits are snapshotted here (Pending)
 * instead of being written to the live `companies` row; a reviewer approves
 * (snapshot applied) or rejects with a note (customer amends & resubmits).
 */
export class CreateCompanyChangeRequest2000000000000
  implements MigrationInterface
{
  name = 'CreateCompanyChangeRequest2000000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.createTable(
      new Table({
        schema: 'freight',
        name: 'company_change_request',
        columns: [
          { name: 'id', type: 'uuid', isPrimary: true, generationStrategy: 'uuid', default: 'gen_random_uuid()' },
          { name: 'company_id', type: 'uuid' },
          { name: 'snapshot', type: 'jsonb' },
          { name: 'documents', type: 'jsonb', isNullable: true },
          { name: 'status', type: 'varchar', length: '20', default: "'pending'" },
          { name: 'note', type: 'text', isNullable: true },
          { name: 'submitted_by', type: 'uuid', isNullable: true },
          { name: 'submitted_at', type: 'timestamptz', isNullable: true },
          { name: 'reviewed_by', type: 'uuid', isNullable: true },
          { name: 'reviewed_at', type: 'timestamptz', isNullable: true },
          { name: 'created_at', type: 'timestamptz', default: 'now()' },
          { name: 'updated_at', type: 'timestamptz', default: 'now()' },
          { name: 'deleted_at', type: 'timestamptz', isNullable: true },
        ],
        foreignKeys: [
          {
            columnNames: ['company_id'],
            referencedSchema: 'freight',
            referencedTableName: 'companies',
            referencedColumnNames: ['id'],
            onDelete: 'CASCADE',
          },
        ],
      }),
      true,
    );

    await queryRunner.createIndex(
      'freight.company_change_request',
      new TableIndex({ name: 'idx_company_change_request_company', columnNames: ['company_id'] }),
    );
    await queryRunner.createIndex(
      'freight.company_change_request',
      new TableIndex({ name: 'idx_company_change_request_status', columnNames: ['status'] }),
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.dropTable('freight.company_change_request', true);
  }
}
