import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Creates the generic dropdown settings tables (freight.dropdown_settings +
 * freight.dropdown_options) backing the DropdownSetting / DropdownOption
 * entities. These tables previously only existed via `synchronize` on some
 * databases; this migration makes them part of the migration history so the
 * SeedGeneralContractPeriod migration (which inserts into them) can run on a
 * fresh database. Idempotent so it is safe on DBs where the tables already exist.
 */
export class CreateDropdownSettings1791999999999
  implements MigrationInterface
{
  name = 'CreateDropdownSettings1791999999999';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS "freight"."dropdown_settings" (
        "id" uuid NOT NULL DEFAULT gen_random_uuid(),
        "code" varchar(128) NOT NULL,
        "label" varchar(256) NOT NULL,
        "description" text,
        "multiple" boolean NOT NULL DEFAULT false,
        "meta" jsonb,
        "created_at" timestamptz NOT NULL DEFAULT now(),
        "updated_at" timestamptz NOT NULL DEFAULT now(),
        "deleted_at" timestamptz,
        CONSTRAINT "PK_dropdown_settings" PRIMARY KEY ("id")
      );
    `);

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

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS "freight"."dropdown_options" (
        "id" uuid NOT NULL DEFAULT gen_random_uuid(),
        "setting_id" uuid NOT NULL,
        "value" varchar(256) NOT NULL,
        "label" varchar(256) NOT NULL,
        "note" text,
        "is_disabled" boolean NOT NULL DEFAULT false,
        "display_order" integer NOT NULL DEFAULT 0,
        "meta" jsonb,
        "created_at" timestamptz NOT NULL DEFAULT now(),
        "updated_at" timestamptz NOT NULL DEFAULT now(),
        "deleted_at" timestamptz,
        CONSTRAINT "PK_dropdown_options" PRIMARY KEY ("id"),
        CONSTRAINT "FK_dropdown_options_setting" FOREIGN KEY ("setting_id")
          REFERENCES "freight"."dropdown_settings" ("id") ON DELETE CASCADE
      );
    `);

    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_dropdown_options_setting_value"
        ON "freight"."dropdown_options" ("setting_id", "value");
    `);
  }

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