import type { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * One photo / video table per module (hotels, activities, vehicles,
 * destinations, trip sources, service types, vehicle types). Each row
 * points at its parent via a real FK. Files live under
 * `uploads/{subdomain}/{module}/`; removed rows are soft-deleted and
 * their file moved to `uploads/deleted/{subdomain}/{module}/`.
 *
 * `activities.cover_image` / `activities.gallery` are left in place
 * (no longer written) — no data is copied by this migration.
 */
const MEDIA_TABLES: { table: string; parentTable: string; parentColumn: string }[] = [
  { table: 'hotel_media', parentTable: 'hotels', parentColumn: 'hotel_id' },
  { table: 'activity_media', parentTable: 'activities', parentColumn: 'activity_id' },
  { table: 'vehicle_media', parentTable: 'vehicles', parentColumn: 'vehicle_id' },
  { table: 'destination_media', parentTable: 'destinations', parentColumn: 'destination_id' },
  { table: 'trip_source_media', parentTable: 'trip_sources', parentColumn: 'trip_source_id' },
  { table: 'service_type_media', parentTable: 'service_types', parentColumn: 'service_type_id' },
  { table: 'vehicle_type_media', parentTable: 'vehicle_types', parentColumn: 'vehicle_type_id' },
];

export class ModuleMediaTables1787100000000 implements MigrationInterface {
  name = 'ModuleMediaTables1787100000000';

  public async up(qr: QueryRunner): Promise<void> {
    for (const { table, parentTable, parentColumn } of MEDIA_TABLES) {
      await qr.query(`
        CREATE TABLE IF NOT EXISTS "${table}" (
          "id" uuid NOT NULL DEFAULT gen_random_uuid(),
          "tenant_id" uuid NOT NULL,
          "${parentColumn}" uuid NOT NULL,
          "url" varchar(500) NOT NULL,
          "media_type" varchar(10) NOT NULL,
          "filename" varchar(255) NOT NULL,
          "is_cover" boolean NOT NULL DEFAULT false,
          "sort_order" int NOT NULL DEFAULT 0,
          "created_by" uuid NULL,
          "updated_by" uuid NULL,
          "created_at" timestamptz NOT NULL DEFAULT now(),
          "updated_at" timestamptz NOT NULL DEFAULT now(),
          "is_deleted" boolean NOT NULL DEFAULT false,
          CONSTRAINT "PK_${table}" PRIMARY KEY ("id"),
          CONSTRAINT "FK_${table}_${parentColumn}" FOREIGN KEY ("${parentColumn}")
            REFERENCES "${parentTable}"("id") ON DELETE NO ACTION,
          CONSTRAINT "CHK_${table}_media_type" CHECK ("media_type" IN ('image', 'video'))
        )
      `);
      await qr.query(
        `CREATE INDEX IF NOT EXISTS "IDX_${table}_tenant" ON "${table}" ("tenant_id")`,
      );
      await qr.query(
        `CREATE INDEX IF NOT EXISTS "IDX_${table}_tenant_parent" ON "${table}" ("tenant_id", "${parentColumn}")`,
      );
    }
  }

  public async down(qr: QueryRunner): Promise<void> {
    for (const { table } of [...MEDIA_TABLES].reverse()) {
      await qr.query(`DROP TABLE IF EXISTS "${table}"`);
    }
  }
}
