-- AlterTable
ALTER TABLE "Category" ADD COLUMN "slug" TEXT;

-- Backfill from nameEn (latin slug). Keep unique with id suffix on collision.
UPDATE "Category" AS c
SET "slug" = lower(
  regexp_replace(
    regexp_replace(trim(c."nameEn"), '[^a-zA-Z0-9]+', '-', 'g'),
    '(^-+|-+$)',
    '',
    'g'
  )
);

UPDATE "Category"
SET "slug" = 'category'
WHERE "slug" IS NULL OR "slug" = '';

UPDATE "Category" AS c
SET "slug" = c."slug" || '-' || right(c."id", 4)
WHERE c."id" IN (
  SELECT id FROM (
    SELECT id, ROW_NUMBER() OVER (PARTITION BY slug ORDER BY "createdAt", id) AS rn
    FROM "Category"
  ) d
  WHERE rn > 1
);

ALTER TABLE "Category" ALTER COLUMN "slug" SET NOT NULL;

-- Prefer readable Persian-romanized top-level slugs
UPDATE "Category" SET "slug" = 'shirini' WHERE "nameFa" = 'شیرینی' AND "parentId" IS NULL;
UPDATE "Category" SET "slug" = 'cake' WHERE "nameFa" = 'کیک' AND "parentId" IS NULL;
UPDATE "Category" SET "slug" = 'shirini-tar' WHERE "nameFa" = 'شیرینی تر';
UPDATE "Category" SET "slug" = 'shirini-khoshk' WHERE "nameFa" = 'شیرینی خشک';
UPDATE "Category" SET "slug" = 'cream-cake' WHERE "nameFa" = 'کیک خامه';

CREATE UNIQUE INDEX "Category_slug_key" ON "Category"("slug");
