import { MigrationInterface, QueryRunner } from "typeorm";

// RECONCILIACION. AddPublicCotizacionFlow1761300000000 creo
// decision_cliente_firma como TEXT (limite real en MySQL: 65,535 bytes).
// PublicDecisionDto.firma (public-decision.dto.ts) y
// CotizacionesService.validatePublicSignature (cotizaciones.service.ts)
// aceptan data URLs de hasta 1,500,000 caracteres -- y desde que el pad de
// firma se ajusta al devicePixelRatio real del telefono
// (frontend/src/lib/signature-pad.ts), una firma real con trazo cargado
// facilmente supera los 65KB del TEXT. Ninguna validacion de la app lo
// atrapaba antes de llegar a MySQL: el INSERT fallaba con
// ER_DATA_TOO_LONG, no hay exception filter que lo traduzca, y el cliente
// veia un 500 "Internal server error" crudo justo al aceptar la
// cotizacion (el momento en el que mas importa que no falle).
//
// MEDIUMTEXT (16,777,215 bytes) cubre con margen el limite de la propia
// app. Ensanchar nunca pierde datos -- seguro de aplicar siempre.
export class WidenCotizacionDecisionFirma1781000000000
  implements MigrationInterface
{
  public async up(queryRunner: QueryRunner): Promise<void> {
    const table = await queryRunner.getTable("taller_cotizaciones");
    if (!table) return;

    const firma = table.findColumnByName("decision_cliente_firma");
    if (firma && firma.type !== "mediumtext") {
      await queryRunner.query(
        "ALTER TABLE taller_cotizaciones MODIFY COLUMN decision_cliente_firma MEDIUMTEXT NULL",
      );
    }
  }

  // Angostar mediumtext->text SI puede perder datos (una firma real ya
  // guardada de mas de 65KB). Se verifica ANTES de tocar la columna --
  // ABORTA si encuentra alguna, en vez de truncar silenciosamente.
  public async down(queryRunner: QueryRunner): Promise<void> {
    const table = await queryRunner.getTable("taller_cotizaciones");
    if (!table) return;

    const firma = table.findColumnByName("decision_cliente_firma");
    if (!firma || firma.type !== "mediumtext") return; // no la puso esta migracion

    const largas = await queryRunner.query(
      `SELECT id FROM taller_cotizaciones WHERE CHAR_LENGTH(decision_cliente_firma) > 65535 LIMIT 1`,
    );
    if (largas.length > 0) {
      throw new Error(
        `No se puede revertir WidenCotizacionDecisionFirma1781000000000: la cotizacion id=${largas[0].id} ` +
          `tiene una firma de mas de 65535 caracteres. Angostar a TEXT la truncaria. ABORTA.`,
      );
    }

    await queryRunner.query(
      "ALTER TABLE taller_cotizaciones MODIFY COLUMN decision_cliente_firma TEXT NULL",
    );
  }
}
