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

export class CreateRecipeIngredientTable1758959442589
  implements MigrationInterface
{
  public async up(queryRunner: QueryRunner): Promise<void> {
    // Create table
    await queryRunner.createTable(
      new Table({
        name: "recipe_ingredient",
        columns: [
          {
            name: "id",
            type: "uuid",
            isPrimary: true,
            isGenerated: true,
            generationStrategy: "uuid",
          },
          {
            name: "create_date",
            type: "timestamp",
            default: "now()",
          },
          {
            name: "update_date",
            type: "timestamp",
            default: "now()",
          },
          {
            name: "title",
            type: "varchar",
            isNullable: false,
          },
          {
            name: "sortOrder",
            type: "int",
            isNullable: false,
          },
          {
            name: "recipe_ingredient_group_id", // foreign key column
            type: "uuid",
            isNullable: false,
          },
        ],
      }),
      true
    );

    // Add foreign key to recipe table
    await queryRunner.createForeignKey(
      "recipe_ingredient",
      new TableForeignKey({
        columnNames: ["recipe_ingredient_group_id"],
        referencedTableName: "recipe_ingredient_group",
        referencedColumnNames: ["id"],
        onDelete: "CASCADE", // delete ingredient if ingredient_group is deleted
      })
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Drop foreign key first
    const table = await queryRunner.getTable("recipe_ingredient");
    const foreignKey = table?.foreignKeys.find(
      (fk) => fk.columnNames.indexOf("recipe_ingredient_group_id") !== -1
    );
    if (foreignKey) {
      await queryRunner.dropForeignKey("recipe_ingredient", foreignKey);
    }

    // Drop table
    await queryRunner.dropTable("recipe_ingredient");
  }
}
