import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`ALTER TABLE "server_plugin_requirements" ADD COLUMN "installUrl" TEXT`);
    await queryRunner.query(`ALTER TABLE "server_plugin_requirements" ADD COLUMN "sourceUrl" TEXT`);
    await queryRunner.query(`ALTER TABLE "server_plugin_requirements" ADD COLUMN "manifestJson" TEXT`);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`CREATE TABLE "temporary_server_plugin_requirements" (
      "serverId"     TEXT NOT NULL,
      "pluginId"     TEXT NOT NULL,
      "status"       TEXT NOT NULL,
      "versionRange" TEXT,
      "reason"       TEXT,
      "configuredBy" TEXT,
      "createdAt"    INTEGER NOT NULL,
      "updatedAt"    INTEGER NOT NULL,
      PRIMARY KEY ("serverId", "pluginId")
    )`);
    await queryRunner.query(`INSERT INTO "temporary_server_plugin_requirements" ("serverId", "pluginId", "status", "versionRange", "reason", "configuredBy", "createdAt", "updatedAt")
      SELECT "serverId", "pluginId", "status", "versionRange", "reason", "configuredBy", "createdAt", "updatedAt" FROM "server_plugin_requirements"`);
    await queryRunner.query(`DROP TABLE "server_plugin_requirements"`);
    await queryRunner.query(`ALTER TABLE "temporary_server_plugin_requirements" RENAME TO "server_plugin_requirements"`);
    await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_server_plugin_requirements_status" ON "server_plugin_requirements" ("status")`);
  }
}
