import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * 为 conversation-service 的三张表添加 tenant_id 列
 *
 * 影响的表：
 * - conversations
 * - messages
 * - token_usages
 *
 * 使用默认租户 ID 回填现有数据
 */
export class AddMultiTenancyToConversationService1738900000000
  implements MigrationInterface
{
  name = 'AddMultiTenancyToConversationService1738900000000';

  private readonly DEFAULT_TENANT_ID =
    '00000000-0000-0000-0000-000000000001';

  public async up(queryRunner: QueryRunner): Promise<void> {
    // ========== 1. conversations 表 ==========
    await queryRunner.query(
      `ALTER TABLE "conversations" ADD COLUMN IF NOT EXISTS "tenant_id" UUID`,
    );
    await queryRunner.query(
      `UPDATE "conversations" SET "tenant_id" = '${this.DEFAULT_TENANT_ID}' WHERE "tenant_id" IS NULL`,
    );
    await queryRunner.query(
      `ALTER TABLE "conversations" ALTER COLUMN "tenant_id" SET NOT NULL`,
    );
    await queryRunner.query(
      `ALTER TABLE "conversations" ALTER COLUMN "tenant_id" SET DEFAULT '${this.DEFAULT_TENANT_ID}'`,
    );
    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS "idx_conversations_tenant" ON "conversations" ("tenant_id")`,
    );
    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS "idx_conversations_tenant_user" ON "conversations" ("tenant_id", "user_id")`,
    );
    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS "idx_conversations_tenant_status" ON "conversations" ("tenant_id", "status")`,
    );

    // ========== 2. messages 表 ==========
    await queryRunner.query(
      `ALTER TABLE "messages" ADD COLUMN IF NOT EXISTS "tenant_id" UUID`,
    );
    await queryRunner.query(
      `UPDATE "messages" SET "tenant_id" = '${this.DEFAULT_TENANT_ID}' WHERE "tenant_id" IS NULL`,
    );
    await queryRunner.query(
      `ALTER TABLE "messages" ALTER COLUMN "tenant_id" SET NOT NULL`,
    );
    await queryRunner.query(
      `ALTER TABLE "messages" ALTER COLUMN "tenant_id" SET DEFAULT '${this.DEFAULT_TENANT_ID}'`,
    );
    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS "idx_messages_tenant" ON "messages" ("tenant_id")`,
    );

    // ========== 3. token_usages 表 ==========
    await queryRunner.query(
      `ALTER TABLE "token_usages" ADD COLUMN IF NOT EXISTS "tenant_id" UUID`,
    );
    await queryRunner.query(
      `UPDATE "token_usages" SET "tenant_id" = '${this.DEFAULT_TENANT_ID}' WHERE "tenant_id" IS NULL`,
    );
    await queryRunner.query(
      `ALTER TABLE "token_usages" ALTER COLUMN "tenant_id" SET NOT NULL`,
    );
    await queryRunner.query(
      `ALTER TABLE "token_usages" ALTER COLUMN "tenant_id" SET DEFAULT '${this.DEFAULT_TENANT_ID}'`,
    );
    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS "idx_token_usages_tenant" ON "token_usages" ("tenant_id")`,
    );

    // ========== 4. 确保 tenants 表存在并有默认租户 ==========
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS "tenants" (
        "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        "name" VARCHAR(100) NOT NULL UNIQUE,
        "slug" VARCHAR(50) NOT NULL UNIQUE,
        "status" VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
        "plan" VARCHAR(30) NOT NULL DEFAULT 'STANDARD',
        "max_users" INT NOT NULL DEFAULT 100,
        "max_conversations_per_month" INT NOT NULL DEFAULT 10000,
        "max_storage_mb" INT NOT NULL DEFAULT 5120,
        "current_user_count" INT NOT NULL DEFAULT 0,
        "current_conversation_count" INT NOT NULL DEFAULT 0,
        "current_storage_bytes" BIGINT NOT NULL DEFAULT 0,
        "config" JSONB NOT NULL DEFAULT '{}',
        "billing_email" VARCHAR(255),
        "billing_name" VARCHAR(100),
        "billing_phone" VARCHAR(20),
        "created_at" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        "updated_at" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        "suspended_at" TIMESTAMPTZ
      )
    `);

    await queryRunner.query(`
      INSERT INTO "tenants" ("id", "name", "slug", "status", "plan")
      VALUES ('${this.DEFAULT_TENANT_ID}', 'Default Tenant', 'default', 'ACTIVE', 'ENTERPRISE')
      ON CONFLICT ("id") DO NOTHING
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // token_usages
    await queryRunner.query(
      `DROP INDEX IF EXISTS "idx_token_usages_tenant"`,
    );
    await queryRunner.query(
      `ALTER TABLE "token_usages" DROP COLUMN IF EXISTS "tenant_id"`,
    );

    // messages
    await queryRunner.query(
      `DROP INDEX IF EXISTS "idx_messages_tenant"`,
    );
    await queryRunner.query(
      `ALTER TABLE "messages" DROP COLUMN IF EXISTS "tenant_id"`,
    );

    // conversations
    await queryRunner.query(
      `DROP INDEX IF EXISTS "idx_conversations_tenant_status"`,
    );
    await queryRunner.query(
      `DROP INDEX IF EXISTS "idx_conversations_tenant_user"`,
    );
    await queryRunner.query(
      `DROP INDEX IF EXISTS "idx_conversations_tenant"`,
    );
    await queryRunner.query(
      `ALTER TABLE "conversations" DROP COLUMN IF EXISTS "tenant_id"`,
    );
  }
}
