/**
 * F-120: Allow deleting a category by cascading to its children and the
 * product-category links that point at it.
 *
 * - catalog_product_categories.category_id: ON DELETE CASCADE — when a product
 *   loses all its categories it is fine; the product itself stays active.
 * - categories_categories.parent_id: ON DELETE CASCADE — child categories are
 *   removed along with their parent so admins can prune a branch in one go.
 *
 * @param {import('node-pg-migrate').MigrationBuilder} pgm
 */
export const up = (pgm) => {
  pgm.sql(
    'ALTER TABLE catalog_product_categories DROP CONSTRAINT IF EXISTS catalog_product_categories_category_id_fkey',
  );
  pgm.sql(
    `ALTER TABLE catalog_product_categories
       ADD CONSTRAINT catalog_product_categories_category_id_fkey
       FOREIGN KEY (category_id) REFERENCES categories_categories(id) ON DELETE CASCADE`,
  );
  pgm.sql(
    'ALTER TABLE categories_categories DROP CONSTRAINT IF EXISTS categories_categories_parent_id_fkey',
  );
  pgm.sql(
    `ALTER TABLE categories_categories
       ADD CONSTRAINT categories_categories_parent_id_fkey
       FOREIGN KEY (parent_id) REFERENCES categories_categories(id) ON DELETE CASCADE`,
  );
};

export const down = (pgm) => {
  pgm.sql(
    'ALTER TABLE catalog_product_categories DROP CONSTRAINT IF EXISTS catalog_product_categories_category_id_fkey',
  );
  pgm.sql(
    `ALTER TABLE catalog_product_categories
       ADD CONSTRAINT catalog_product_categories_category_id_fkey
       FOREIGN KEY (category_id) REFERENCES categories_categories(id) ON DELETE RESTRICT`,
  );
  pgm.sql(
    'ALTER TABLE categories_categories DROP CONSTRAINT IF EXISTS categories_categories_parent_id_fkey',
  );
  pgm.sql(
    `ALTER TABLE categories_categories
       ADD CONSTRAINT categories_categories_parent_id_fkey
       FOREIGN KEY (parent_id) REFERENCES categories_categories(id) ON DELETE RESTRICT`,
  );
};
