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

export class CreateOtEventos1761100000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.createTable(
      new Table({
        name: "taller_ot_eventos",
        columns: [
          {
            name: "id",
            type: "int",
            isPrimary: true,
            isGenerated: true,
            generationStrategy: "increment",
          },
          { name: "ot_id", type: "int" },
          {
            name: "tipo",
            type: "enum",
            enum: [
              "creacion",
              "cambio_estado",
              "evidencia_agregada",
              "producto_agregado",
              "cotizacion_aprobada",
              "firma_capturada",
              "otro",
            ],
            default: "'otro'",
          },
          { name: "descripcion", type: "text" },
          { name: "usuario_id", type: "int", isNullable: true },
          {
            name: "created_at",
            type: "timestamp",
            default: "CURRENT_TIMESTAMP",
          },
        ],
      }),
      true,
    );

    await queryRunner.createIndex(
      "taller_ot_eventos",
      new TableIndex({
        name: "IDX_ot_eventos_ot",
        columnNames: ["ot_id"],
      }),
    );

    await queryRunner.createIndex(
      "taller_ot_eventos",
      new TableIndex({
        name: "IDX_ot_eventos_created",
        columnNames: ["created_at"],
      }),
    );

    await queryRunner.createForeignKey(
      "taller_ot_eventos",
      new TableForeignKey({
        columnNames: ["ot_id"],
        referencedTableName: "taller_ordenes_trabajo",
        referencedColumnNames: ["id"],
        onDelete: "CASCADE",
      }),
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.dropTable("taller_ot_eventos", true);
  }
}
