import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    const columns = await queryRunner.query(`PRAGMA table_info("plugin_data")`) as Array<{ name?: string }>;
    const hasOwnerUserId = columns.some((column) => column.name === 'ownerUserId');

    if (hasOwnerUserId) {
      return;
    }

    const metaRows = await queryRunner.query(`SELECT "value" FROM "meta" WHERE "key" = 'currentUserId' LIMIT 1`) as Array<{ value?: string | null }>;
    const currentUserId = metaRows[0]?.value?.trim() ?? '';

    await queryRunner.query(`
      CREATE TABLE "temporary_plugin_data" (
        "ownerUserId" TEXT NOT NULL,
        "pluginId"    TEXT NOT NULL,
        "scope"       TEXT NOT NULL,
        "serverId"    TEXT NOT NULL,
        "key"         TEXT NOT NULL,
        "valueJson"   TEXT NOT NULL,
        "updatedAt"   INTEGER NOT NULL,
        PRIMARY KEY ("ownerUserId", "pluginId", "scope", "serverId", "key")
      )
    `);
    await queryRunner.query(
      `INSERT INTO "temporary_plugin_data" ("ownerUserId", "pluginId", "scope", "serverId", "key", "valueJson", "updatedAt")
       SELECT ?, "pluginId", "scope", "serverId", "key", "valueJson", "updatedAt" FROM "plugin_data"`,
      [currentUserId]
    );
    await queryRunner.query(`DROP TABLE "plugin_data"`);
    await queryRunner.query(`ALTER TABLE "temporary_plugin_data" RENAME TO "plugin_data"`);
    await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_plugin_data_owner_plugin_scope" ON "plugin_data" ("ownerUserId", "pluginId", "scope")`);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`CREATE TABLE "temporary_plugin_data" (
      "pluginId"  TEXT NOT NULL,
      "scope"     TEXT NOT NULL,
      "serverId"  TEXT NOT NULL,
      "key"       TEXT NOT NULL,
      "valueJson" TEXT NOT NULL,
      "updatedAt" INTEGER NOT NULL,
      PRIMARY KEY ("pluginId", "scope", "serverId", "key")
    )`);
    await queryRunner.query(`INSERT OR REPLACE INTO "temporary_plugin_data" ("pluginId", "scope", "serverId", "key", "valueJson", "updatedAt")
      SELECT "pluginId", "scope", "serverId", "key", "valueJson", "updatedAt" FROM "plugin_data"`);
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_plugin_data_owner_plugin_scope"`);
    await queryRunner.query(`DROP TABLE "plugin_data"`);
    await queryRunner.query(`ALTER TABLE "temporary_plugin_data" RENAME TO "plugin_data"`);
    await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_plugin_data_plugin_scope" ON "plugin_data" ("pluginId", "scope")`);
  }
}
