import {
  MigrationInterface,
  QueryRunner,
  Table,
  TableIndex,
} from "typeorm";

export class CreateCotizacionLocks1761200000000
  implements MigrationInterface
{
  public async up(queryRunner: QueryRunner): Promise<void> {
    const exists = await queryRunner.hasTable("taller_cotizacion_locks");
    if (exists) return;

    await queryRunner.createTable(
      new Table({
        name: "taller_cotizacion_locks",
        columns: [
          { name: "id", type: "int", isPrimary: true, isGenerated: true, generationStrategy: "increment" },
          { name: "cotizacion_id", type: "int", isUnique: true },
          { name: "token", type: "varchar", length: "36" },
          { name: "usuario_id", type: "int" },
          { name: "usuario_nombre", type: "varchar", length: "255", isNullable: true },
          { name: "expires_at", type: "datetime" },
          { name: "created_at", type: "timestamp", default: "CURRENT_TIMESTAMP" },
          {
            name: "updated_at",
            type: "timestamp",
            default: "CURRENT_TIMESTAMP",
            onUpdate: "CURRENT_TIMESTAMP",
          },
        ],
      }),
    );

    await queryRunner.createIndex(
      "taller_cotizacion_locks",
      new TableIndex({
        name: "IDX_cotizacion_lock_cotizacion",
        columnNames: ["cotizacion_id"],
      }),
    );
    await queryRunner.createIndex(
      "taller_cotizacion_locks",
      new TableIndex({
        name: "IDX_cotizacion_lock_token",
        columnNames: ["token"],
      }),
    );
    await queryRunner.createIndex(
      "taller_cotizacion_locks",
      new TableIndex({
        name: "IDX_cotizacion_lock_usuario",
        columnNames: ["usuario_id"],
      }),
    );
    await queryRunner.createIndex(
      "taller_cotizacion_locks",
      new TableIndex({
        name: "IDX_cotizacion_lock_expires",
        columnNames: ["expires_at"],
      }),
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.dropTable("taller_cotizacion_locks", true);
  }
}
