-- PBI-59: Sprint.code (SP-1, SP-2, ...) sequentieel per product
--
-- 1. Voeg nullable kolom toe
-- 2. Backfill bestaande rijen via ROW_NUMBER() per product op created_at
-- 3. Maak NOT NULL en voeg unieke index toe op (product_id, code)

ALTER TABLE "sprints" ADD COLUMN "code" VARCHAR(30);

WITH numbered AS (
  SELECT
    id,
    product_id,
    ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY created_at, id) AS n
  FROM "sprints"
)
UPDATE "sprints" s
SET code = 'SP-' || numbered.n
FROM numbered
WHERE s.id = numbered.id;

ALTER TABLE "sprints" ALTER COLUMN "code" SET NOT NULL;

CREATE UNIQUE INDEX "sprints_product_id_code_key" ON "sprints"("product_id", "code");
