import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * In-app notification inbox. One row per recipient per logical notification;
 * producers fan out by inserting many rows. Indexed for the two hot queries:
 * unread-count (recipient + is_read) and the newest-first list (recipient +
 * created_at). Enum-like columns are stored as varchar to avoid PG enum churn.
 */
export class CreateNotifications1950000000000 implements MigrationInterface {
  name = "CreateNotifications1950000000000";

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.notifications (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        recipient_user_id uuid NOT NULL,
        audience varchar(20) NOT NULL,
        type varchar(48) NOT NULL DEFAULT 'GENERIC',
        title varchar(200) NOT NULL,
        body text NOT NULL,
        link varchar,
        data jsonb,
        priority varchar(12) NOT NULL DEFAULT 'NORMAL',
        is_read boolean NOT NULL DEFAULT false,
        read_at timestamptz,
        channels_sent jsonb,
        created_at timestamptz NOT NULL DEFAULT now(),
        updated_at timestamptz NOT NULL DEFAULT now(),
        deleted_at timestamptz
      )
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_NOTIFICATIONS_RECIPIENT_UNREAD"
      ON freight.notifications (recipient_user_id, is_read)
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_NOTIFICATIONS_RECIPIENT_CREATED"
      ON freight.notifications (recipient_user_id, created_at)
    `);
  }

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