import { MigrationInterface, QueryRunner } from "typeorm";

// Los sitios NUEVOS ya no deben arrancar con tiendas/productos/facturacion
// encendidos: el default operativo vive en el catalogo de taller_parametros
// (apagado) y esta migracion baja el DEFAULT de las columnas a 0.
//
// Pero un tenant que ya existe y NUNCA tuvo fila en tenant_config se comportaba
// como "todo encendido" (getTogglesOperativos devolvia true para quien no tenia
// fila). Si solo se cambiara el default, esos tenants pasarian a "todo apagado"
// de un dia para otro. Por eso, ANTES de bajar el default, se les crea una fila
// explicita con todo en 1: conservan exactamente lo que tenian, y solo los
// tenants creados despues de esta migracion heredan el default apagado. Los
// valores de las filas que ya existian no se tocan.
export class SetTenantConfigTogglesDefaultOff1781300000000 implements MigrationInterface {
  name = "SetTenantConfigTogglesDefaultOff1781300000000";

  public async up(queryRunner: QueryRunner): Promise<void> {
    await this.respaldarTenantsSinFila(queryRunner);
    await this.cambiarDefault(queryRunner, 0);
  }

  private async respaldarTenantsSinFila(queryRunner: QueryRunner): Promise<void> {
    const config = await queryRunner.getTable("tenant_config");
    if (!config || !(await queryRunner.hasTable("tenants"))) return;
    if (
      !config.findColumnByName("permite_tiendas") ||
      !config.findColumnByName("permite_productos_propios") ||
      !config.findColumnByName("factura_habilitada")
    ) {
      return;
    }

    await queryRunner.query(
      `INSERT INTO tenant_config (tenant_id, permite_tiendas, permite_productos_propios, factura_habilitada)
       SELECT t.id, 1, 1, 1 FROM tenants t
       WHERE NOT EXISTS (SELECT 1 FROM tenant_config c WHERE c.tenant_id = t.id)`,
    );
  }

  // El down solo restaura el DEFAULT: las filas respaldadas son indistinguibles
  // de las que un operador creo a mano, asi que no se borran.
  public async down(queryRunner: QueryRunner): Promise<void> {
    await this.cambiarDefault(queryRunner, 1);
  }

  private async cambiarDefault(
    queryRunner: QueryRunner,
    valor: 0 | 1,
  ): Promise<void> {
    const table = await queryRunner.getTable("tenant_config");
    if (!table) return;

    for (const columna of [
      "permite_tiendas",
      "permite_productos_propios",
      "factura_habilitada",
    ]) {
      if (table.findColumnByName(columna)) {
        await queryRunner.query(
          `ALTER TABLE tenant_config ALTER COLUMN ${columna} SET DEFAULT ${valor}`,
        );
      }
    }
  }
}
