/**
 * Migration: Seed FREE Subscriptions for Existing Organizations
 *
 * Creates a FREE subscription for all existing organizations that don't have one,
 * and assigns licenses to all their active users.
 */

import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Create FREE subscription for each organization that doesn't have one
    await queryRunner.query(`
      INSERT INTO "subscriptions" (
        "id",
        "organization_id",
        "plan",
        "status",
        "created_at",
        "updated_at"
      )
      SELECT
        uuid_generate_v4(),
        o.id,
        'FREE',
        'ACTIVE',
        NOW(),
        NOW()
      FROM "organizations" o
      WHERE NOT EXISTS (
        SELECT 1 FROM "subscriptions" s WHERE s.organization_id = o.id
      )
    `);

    // Assign licenses to all active users in organizations with subscriptions
    await queryRunner.query(`
      INSERT INTO "licenses" (
        "id",
        "subscription_id",
        "user_id",
        "status",
        "assigned_at"
      )
      SELECT
        uuid_generate_v4(),
        s.id,
        u.id,
        'ACTIVE',
        NOW()
      FROM "users" u
      INNER JOIN "subscriptions" s ON s.organization_id = u.organization_id
      WHERE u.is_active = true
      AND NOT EXISTS (
        SELECT 1 FROM "licenses" l WHERE l.user_id = u.id
      )
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Remove licenses created by this migration
    // Note: This is a destructive operation that cannot perfectly reverse
    // We'll delete all licenses and subscriptions with FREE plan created after a certain point
    // In practice, you wouldn't typically revert this in production

    await queryRunner.query(`
      DELETE FROM "licenses"
    `);

    await queryRunner.query(`
      DELETE FROM "subscriptions" WHERE "plan" = 'FREE'
    `);
  }
}
