import { MigrationInterface, QueryRunner } from "typeorm";

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    const maetieExists = await queryRunner.hasTable("maetie");
    if (!maetieExists) {
      return;
    }

    const [defaultStore] = await queryRunner.query(
      "SELECT tienda FROM maetie WHERE (status IS NULL OR status <> 1) AND (alta IS NULL OR alta <> 'N') AND (es_transito IS NULL OR es_transito <> 'S') ORDER BY tienda ASC LIMIT 1",
    );
    const defaultStoreId = defaultStore?.tienda ?? null;

    if (defaultStoreId) {
      await queryRunner.query(
        "UPDATE taller_usuarios u LEFT JOIN maetie t ON t.tienda = u.tienda_id SET u.tienda_id = ? WHERE u.tienda_id IS NULL OR t.tienda IS NULL",
        [defaultStoreId],
      );
      await queryRunner.query(
        "UPDATE taller_ordenes_trabajo ot LEFT JOIN maetie t ON t.tienda = ot.tienda_id SET ot.tienda_id = ? WHERE ot.tienda_id IS NULL OR t.tienda IS NULL",
        [defaultStoreId],
      );
    }

    const tallerTiendasExists = await queryRunner.hasTable("taller_tiendas");
    if (tallerTiendasExists) {
      await queryRunner.dropTable("taller_tiendas", true);
    }
  }

  public async down(): Promise<void> {
    // No se recrea taller_tiendas: maetie es el maestro real de tiendas.
  }
}
