import { MigrationInterface, QueryRunner } from "typeorm";

// RECONCILIACION, la mas delicada de esta tanda: CreateTallerTables1738852000000
// dejo taller_ot_danos.zona en varchar(100) DEFAULT NULL; la entidad
// (OtDano.zona, sin nullable => NOT NULL) y la demo real coinciden en
// varchar(50) NOT NULL. Angostar Y volver NOT NULL a la vez puede fallar o
// truncar si hay datos incompatibles — se verifica ANTES de tocar la
// columna, y se aborta con un mensaje claro en cualquiera de los dos casos
// en vez de dejar que MySQL trunque o falle con un error generico.
export class ReconcileOtDanosZona1770400000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    const table = await queryRunner.getTable("taller_ot_danos");
    if (!table) return;

    const zona = table.findColumnByName("zona");
    if (!zona) return; // no deberia pasar, defensivo igual
    if (zona.length === "50" && !zona.isNullable) return; // ya esta bien (ej. la demo)

    const nulos = await queryRunner.query(
      `SELECT COUNT(*) as c FROM taller_ot_danos WHERE zona IS NULL`,
    );
    if (Number(nulos[0].c) > 0) {
      throw new Error(
        `No se puede volver taller_ot_danos.zona NOT NULL: hay ${nulos[0].c} fila(s) con zona=NULL. ` +
          "Decidir a mano que valor les corresponde antes de reintentar — no hay un default seguro para 'zona'.",
      );
    }

    const largas = await queryRunner.query(
      `SELECT id, CHAR_LENGTH(zona) as len FROM taller_ot_danos WHERE CHAR_LENGTH(zona) > 50 LIMIT 1`,
    );
    if (largas.length > 0) {
      throw new Error(
        `No se puede achicar taller_ot_danos.zona a varchar(50): la fila id=${largas[0].id} ` +
          `tiene ${largas[0].len} caracteres. Decidir a mano antes de reintentar.`,
      );
    }

    await queryRunner.query(
      "ALTER TABLE taller_ot_danos MODIFY COLUMN zona varchar(50) NOT NULL",
    );
  }

  // Seguro de revertir de verdad: ensanchar (50->100) y volver a nullable
  // nunca pierden datos — todo lo que entraba en varchar(50) NOT NULL sigue
  // entrando en varchar(100) NULL. Sin riesgo en esta direccion, a
  // diferencia de up().
  public async down(queryRunner: QueryRunner): Promise<void> {
    const table = await queryRunner.getTable("taller_ot_danos");
    if (!table) return;
    const zona = table.findColumnByName("zona");
    if (!zona || zona.length !== "50" || zona.isNullable) return; // no la puso esta migracion

    await queryRunner.query(
      "ALTER TABLE taller_ot_danos MODIFY COLUMN zona varchar(100) NULL",
    );
  }
}
