import { MigrationInterface, QueryRunner, TableColumn } from "typeorm";

// Datos que se capturan al entregar el vehiculo: km y gasolina de salida,
// recomendaciones para el cliente (van en el comprobante) y la firma de quien
// entrega, separada de la firma de recepcion. Todo nullable y aditivo: las OT
// existentes quedan sin esos datos y ningun flujo actual cambia.
const COLUMNAS_OT: TableColumn[] = [
  new TableColumn({ name: "km_salida", type: "int", isNullable: true }),
  new TableColumn({
    name: "nivel_gasolina_salida",
    type: "int",
    isNullable: true,
  }),
  new TableColumn({
    name: "recomendaciones_entrega",
    type: "text",
    isNullable: true,
  }),
];

const COLUMNAS_FIRMA: TableColumn[] = [
  new TableColumn({
    name: "firma_entrega",
    type: "varchar",
    length: "500",
    isNullable: true,
  }),
  new TableColumn({
    name: "nombre_firma_entrega",
    type: "varchar",
    length: "255",
    isNullable: true,
  }),
  new TableColumn({
    name: "fecha_firma_entrega",
    type: "datetime",
    isNullable: true,
  }),
];

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await this.agregar(queryRunner, "taller_ordenes_trabajo", COLUMNAS_OT);
    await this.agregar(queryRunner, "taller_ot_firmas", COLUMNAS_FIRMA);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await this.quitar(queryRunner, "taller_ot_firmas", COLUMNAS_FIRMA);
    await this.quitar(queryRunner, "taller_ordenes_trabajo", COLUMNAS_OT);
  }

  private async agregar(
    queryRunner: QueryRunner,
    tabla: string,
    columnas: TableColumn[],
  ): Promise<void> {
    const table = await queryRunner.getTable(tabla);
    if (!table) return;

    for (const columna of columnas) {
      if (!table.findColumnByName(columna.name)) {
        await queryRunner.addColumn(tabla, columna);
      }
    }
  }

  private async quitar(
    queryRunner: QueryRunner,
    tabla: string,
    columnas: TableColumn[],
  ): Promise<void> {
    const table = await queryRunner.getTable(tabla);
    if (!table) return;

    for (const columna of [...columnas].reverse()) {
      if (table.findColumnByName(columna.name)) {
        await queryRunner.dropColumn(tabla, columna.name);
      }
    }
  }
}
