import { MigrationInterface, QueryRunner, Table } from "typeorm";
import BackupHelper from "../helpers/backupHelper";
import { getTypeByORM } from "./ormHelper";
import InternalException from "../exceptions/internalException";

export class BackupAndResetDatabase1738166124200 implements MigrationInterface {
  name = "BackupAndResetDatabase1738166124200";

  public async up(queryRunner: QueryRunner): Promise<void> {
    if ((await queryRunner.hasTable("user")) && !(await queryRunner.hasTable("salutation"))) {
      throw new InternalException(
        "Cannot update due to skiped version. Update to v1.2.2 Version first to prevent data loss and get access to the newer Versions."
      );
    }

    if (await queryRunner.hasTable("user")) {
      await BackupHelper.createBackup({ collectIds: false });
    }
    await queryRunner.clearDatabase();

    await queryRunner.createTable(
      new Table({
        name: "migrations",
        columns: [
          {
            name: "id",
            type: getTypeByORM("int"),
            isPrimary: true,
            isGenerated: true,
            generationStrategy: "increment",
          },
          { name: "timestamp", type: getTypeByORM("bigint"), isNullable: false },
          { name: "name", type: getTypeByORM("varchar"), length: "255", isNullable: false },
        ],
      }),
      true
    );

    await queryRunner.createTable(
      new Table({
        name: "typeorm_metadata",
        columns: [
          { name: "type", type: getTypeByORM("varchar"), length: "255", isNullable: false },
          { name: "database", type: getTypeByORM("varchar"), length: "255", isNullable: true, default: null },
          { name: "schema", type: getTypeByORM("varchar"), length: "255", isNullable: true, default: null },
          { name: "table", type: getTypeByORM("varchar"), length: "255", isNullable: true, default: null },
          { name: "name", type: getTypeByORM("varchar"), length: "255", isNullable: true, default: null },
          { name: "value", type: getTypeByORM("text"), length: "255", isNullable: true, default: null },
        ],
      }),
      true
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {}
}