import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * file_upload_settings / file_upload_fields entities had no migration; seeder requires both tables.
 */
export class CreateFileUploadSettingsTables1749900000000 implements MigrationInterface {
  name = 'CreateFileUploadSettingsTables1749900000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.file_upload_settings (
        id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
        code VARCHAR(128) NOT NULL,
        label VARCHAR(256) NOT NULL,
        description TEXT,
        entity VARCHAR(32) NOT NULL DEFAULT 'other',
        created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        deleted_at TIMESTAMPTZ
      );
    `);

    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_file_upload_settings_code"
        ON freight.file_upload_settings (code);
    `);

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.file_upload_fields (
        id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
        setting_id UUID NOT NULL,
        file_key VARCHAR(128) NOT NULL,
        file_label VARCHAR(256) NOT NULL,
        help_text TEXT,
        is_required BOOLEAN NOT NULL DEFAULT false,
        is_multiple BOOLEAN NOT NULL DEFAULT false,
        max_files INTEGER NOT NULL DEFAULT 1,
        allowed_extensions TEXT[] NOT NULL DEFAULT '{}'::text[],
        max_size_mb INTEGER NOT NULL DEFAULT 10,
        display_order INTEGER NOT NULL DEFAULT 0,
        created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        deleted_at TIMESTAMPTZ,
        CONSTRAINT "CHK_file_upload_fields_max_files" CHECK (max_files > 0),
        CONSTRAINT "CHK_file_upload_fields_max_size_mb" CHECK (max_size_mb > 0),
        CONSTRAINT "FK_file_upload_fields_setting"
          FOREIGN KEY (setting_id)
          REFERENCES freight.file_upload_settings(id)
          ON DELETE CASCADE
      );
    `);

    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_file_upload_fields_setting_file_key"
        ON freight.file_upload_fields (setting_id, file_key);
    `);
  }

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