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

/**
 * Creates the `recipe_tag` many-to-many join table.
 *
 * Both foreign keys are defined with ON DELETE CASCADE so that:
 *   - deleting a Recipe automatically removes its rows from this table, and
 *   - deleting a Tag automatically removes its rows from this table.
 * In both cases the other side of the relation is left untouched.
 */

export class CreateRecipeTagTable1771658131258 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.createTable(
            new Table({
                name: "recipe_tag",
                columns: [
                    {
                        name: "recipe_id",
                        type: "uuid",
                        isPrimary: true,
                    },
                    {
                        name: "tag_id",
                        type: "uuid",
                        isPrimary: true,
                    },
                ],
            }),
            true // ifNotExists
        );

        // FK: recipe_tag.recipe_id → recipe.id  (cascade on recipe delete)
        await queryRunner.createForeignKey(
            "recipe_tag",
            new TableForeignKey({
                name: "FK_recipe_tag_recipe",
                columnNames: ["recipe_id"],
                referencedTableName: "recipe",
                referencedColumnNames: ["id"],
                onDelete: "CASCADE",
                onUpdate: "CASCADE",
            })
        );

        // FK: recipe_tag.tag_id → tag.id  (cascade on tag delete)
        await queryRunner.createForeignKey(
            "recipe_tag",
            new TableForeignKey({
                name: "FK_recipe_tag_tag",
                columnNames: ["tag_id"],
                referencedTableName: "tag",
                referencedColumnNames: ["id"],
                onDelete: "CASCADE",
                onUpdate: "CASCADE",
            })
        );
    }

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