import {
  MigrationInterface,
  QueryRunner,
  Table,
  TableColumn,
  TableForeignKey,
  TableIndex,
} from "typeorm";

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    const mecanicosExists = await queryRunner.hasTable("taller_mecanicos");
    if (!mecanicosExists) {
      await queryRunner.createTable(
        new Table({
          name: "taller_mecanicos",
          columns: [
            {
              name: "id",
              type: "int",
              isPrimary: true,
              isGenerated: true,
              generationStrategy: "increment",
            },
            { name: "nombre", type: "varchar", length: "255" },
            { name: "telefono", type: "varchar", length: "100", isNullable: true },
            { name: "email", type: "varchar", length: "255", isNullable: true },
            {
              name: "especialidad",
              type: "varchar",
              length: "255",
              isNullable: true,
            },
            { name: "tienda_id", type: "int", isNullable: true },
            { name: "activo", type: "boolean", default: true },
            {
              name: "created_at",
              type: "timestamp",
              default: "CURRENT_TIMESTAMP",
            },
            {
              name: "updated_at",
              type: "timestamp",
              default: "CURRENT_TIMESTAMP",
              onUpdate: "CURRENT_TIMESTAMP",
            },
          ],
        }),
      );
      await queryRunner.createIndex(
        "taller_mecanicos",
        new TableIndex({ name: "IDX_mecanicos_nombre", columnNames: ["nombre"] }),
      );
      await queryRunner.createIndex(
        "taller_mecanicos",
        new TableIndex({ name: "IDX_mecanicos_activo", columnNames: ["activo"] }),
      );
      await queryRunner.createIndex(
        "taller_mecanicos",
        new TableIndex({
          name: "IDX_mecanicos_tienda_id",
          columnNames: ["tienda_id"],
        }),
      );
    }

    const ots = await queryRunner.getTable("taller_ordenes_trabajo");
    if (ots && !ots.findColumnByName("mecanico_id")) {
      await queryRunner.addColumn(
        "taller_ordenes_trabajo",
        new TableColumn({
          name: "mecanico_id",
          type: "int",
          isNullable: true,
        }),
      );
      await queryRunner.createIndex(
        "taller_ordenes_trabajo",
        new TableIndex({
          name: "IDX_ots_mecanico_id",
          columnNames: ["mecanico_id"],
        }),
      );
      await queryRunner.createForeignKey(
        "taller_ordenes_trabajo",
        new TableForeignKey({
          name: "FK_ots_mecanico",
          columnNames: ["mecanico_id"],
          referencedTableName: "taller_mecanicos",
          referencedColumnNames: ["id"],
          onDelete: "SET NULL",
        }),
      );
    }

    const productos = await queryRunner.getTable("taller_productos");
    if (productos && !productos.findColumnByName("costo")) {
      await queryRunner.addColumn(
        "taller_productos",
        new TableColumn({
          name: "costo",
          type: "decimal",
          precision: 12,
          scale: 2,
          default: 0,
        }),
      );
    }

    const cotizaciones = await queryRunner.getTable("taller_cotizaciones");
    if (cotizaciones && !cotizaciones.findColumnByName("asesor_id")) {
      await queryRunner.addColumn(
        "taller_cotizaciones",
        new TableColumn({
          name: "asesor_id",
          type: "int",
          isNullable: true,
        }),
      );
      await queryRunner.addColumn(
        "taller_cotizaciones",
        new TableColumn({
          name: "asesor_nombre",
          type: "varchar",
          length: "255",
          isNullable: true,
        }),
      );
      await queryRunner.createIndex(
        "taller_cotizaciones",
        new TableIndex({
          name: "IDX_cotizaciones_asesor_id",
          columnNames: ["asesor_id"],
        }),
      );
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    const cotizaciones = await queryRunner.getTable("taller_cotizaciones");
    if (cotizaciones?.findColumnByName("asesor_id")) {
      const index = cotizaciones.indices.find(
        (item) => item.name === "IDX_cotizaciones_asesor_id",
      );
      if (index) await queryRunner.dropIndex("taller_cotizaciones", index);
      await queryRunner.dropColumn("taller_cotizaciones", "asesor_nombre");
      await queryRunner.dropColumn("taller_cotizaciones", "asesor_id");
    }

    const productos = await queryRunner.getTable("taller_productos");
    if (productos?.findColumnByName("costo")) {
      await queryRunner.dropColumn("taller_productos", "costo");
    }

    const ots = await queryRunner.getTable("taller_ordenes_trabajo");
    if (ots?.findColumnByName("mecanico_id")) {
      const fk = ots.foreignKeys.find((item) => item.name === "FK_ots_mecanico");
      if (fk) await queryRunner.dropForeignKey("taller_ordenes_trabajo", fk);
      const index = ots.indices.find((item) => item.name === "IDX_ots_mecanico_id");
      if (index) await queryRunner.dropIndex("taller_ordenes_trabajo", index);
      await queryRunner.dropColumn("taller_ordenes_trabajo", "mecanico_id");
    }

    await queryRunner.dropTable("taller_mecanicos", true);
  }
}
