/**
 * Migration: Create Licenses Table
 *
 * This table stores user licenses linked to subscriptions.
 * Each active user in an organization consumes one license.
 */

import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Create license_status enum
    await queryRunner.query(`
      CREATE TYPE "license_status_enum" AS ENUM ('ACTIVE', 'REVOKED')
    `);

    // Create licenses table
    await queryRunner.query(`
      CREATE TABLE "licenses" (
        "id" UUID NOT NULL DEFAULT uuid_generate_v4(),
        "subscription_id" UUID NOT NULL,
        "user_id" UUID NOT NULL,

        -- Status
        "status" license_status_enum NOT NULL DEFAULT 'ACTIVE',

        -- Timestamps
        "assigned_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        "revoked_at" TIMESTAMP NULL,

        CONSTRAINT "pk_licenses" PRIMARY KEY ("id"),
        CONSTRAINT "uq_licenses_user_id" UNIQUE ("user_id"),
        CONSTRAINT "fk_licenses_subscription" FOREIGN KEY ("subscription_id")
          REFERENCES "subscriptions"("id") ON DELETE CASCADE,
        CONSTRAINT "fk_licenses_user" FOREIGN KEY ("user_id")
          REFERENCES "users"("id") ON DELETE CASCADE
      )
    `);

    // Create indexes
    await queryRunner.query(`
      CREATE INDEX "idx_licenses_subscription_id" ON "licenses" ("subscription_id")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_licenses_user_id" ON "licenses" ("user_id")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_licenses_status" ON "licenses" ("status")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_licenses_subscription_status" ON "licenses" ("subscription_id", "status")
    `);

    // Add comments
    await queryRunner.query(`
      COMMENT ON TABLE "licenses" IS 'User licenses for subscription-based access control'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "licenses"."status" IS 'ACTIVE: license in use, REVOKED: license freed up'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "licenses"."revoked_at" IS 'Timestamp when license was revoked, NULL if still active'
    `);
  }

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