import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * Session store for the VeriFayda 2.0 OIDC verification flow (ported from
 * passenger-api). One row per started verification; `state` is the
 * single-use CSRF token linking the eSignet redirect back to the session.
 */
export class AddFaydaVerificationSessions1890000000002 implements MigrationInterface {
  name = "AddFaydaVerificationSessions1890000000002";

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.fayda_verification_sessions (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        state varchar NOT NULL UNIQUE,
        code_verifier varchar NOT NULL,
        purpose varchar NOT NULL DEFAULT 'VERIFY',
        platform varchar NOT NULL DEFAULT 'WEB',
        save_to_account boolean NOT NULL DEFAULT false,
        status varchar NOT NULL DEFAULT 'PENDING',
        error_code varchar,
        error_description text,
        iam_user_id uuid,
        expires_at timestamptz NOT NULL,
        completed_at timestamptz,
        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_FAYDA_SESSIONS_EXPIRES_AT"
      ON freight.fayda_verification_sessions (expires_at)
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_FAYDA_SESSIONS_IAM_USER_ID"
      ON freight.fayda_verification_sessions (iam_user_id)
    `);
  }

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