import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Migration: Create API Keys Table
 *
 * Stores API keys for programmatic access.
 * Only GOLD and PLATINIUM subscribers can create keys (enforced at application level).
 *
 * Security: the raw key is NEVER stored — only its SHA-256 hex hash.
 */
export class CreateApiKeysTable1741000000001 implements MigrationInterface {
  name = 'CreateApiKeysTable1741000000001';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE "api_keys" (
        "id"              UUID          NOT NULL DEFAULT uuid_generate_v4(),
        "organization_id" UUID          NOT NULL,
        "user_id"         UUID          NOT NULL,
        "name"            VARCHAR(100)  NOT NULL,
        "key_hash"        VARCHAR(64)   NOT NULL,
        "key_prefix"      VARCHAR(20)   NOT NULL,
        "is_active"       BOOLEAN       NOT NULL DEFAULT TRUE,
        "last_used_at"    TIMESTAMP     NULL,
        "expires_at"      TIMESTAMP     NULL,
        "created_at"      TIMESTAMP     NOT NULL DEFAULT NOW(),
        "updated_at"      TIMESTAMP     NOT NULL DEFAULT NOW(),

        CONSTRAINT "pk_api_keys"               PRIMARY KEY ("id"),
        CONSTRAINT "uq_api_keys_key_hash"      UNIQUE ("key_hash"),
        CONSTRAINT "fk_api_keys_organization"  FOREIGN KEY ("organization_id")
          REFERENCES "organizations"("id") ON DELETE CASCADE,
        CONSTRAINT "fk_api_keys_user"          FOREIGN KEY ("user_id")
          REFERENCES "users"("id") ON DELETE CASCADE
      )
    `);

    await queryRunner.query(
      `CREATE INDEX "idx_api_keys_organization_id" ON "api_keys" ("organization_id")`
    );
    await queryRunner.query(`CREATE INDEX "idx_api_keys_user_id" ON "api_keys" ("user_id")`);
    await queryRunner.query(`CREATE INDEX "idx_api_keys_is_active" ON "api_keys" ("is_active")`);
    await queryRunner.query(`CREATE INDEX "idx_api_keys_key_hash" ON "api_keys" ("key_hash")`);

    await queryRunner.query(
      `COMMENT ON TABLE "api_keys" IS 'API keys for programmatic access — GOLD and PLATINIUM plans only'`
    );
    await queryRunner.query(
      `COMMENT ON COLUMN "api_keys"."key_hash" IS 'SHA-256 hex hash of the raw API key. The raw key is never stored.'`
    );
  }

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