-- C3: Partial unique constraint untuk mencegah race condition duplicate invoice
-- Dokumen yang sudah ada invoice aktif (non-deleted, non-extend) tidak boleh
-- punya invoice aktif lagi.

CREATE UNIQUE INDEX "invoices_btd_active_unique"
  ON "invoices" ("btdDokumenId")
  WHERE "deletedAt" IS NULL
    AND "btdDokumenId" IS NOT NULL
    AND ("detailSnapshot"->>'isExtend' IS NULL OR "detailSnapshot"->>'isExtend' = 'false');

CREATE UNIQUE INDEX "invoices_bdn_active_unique"
  ON "invoices" ("bdnDokumenId")
  WHERE "deletedAt" IS NULL
    AND "bdnDokumenId" IS NOT NULL
    AND ("detailSnapshot"->>'isExtend' IS NULL OR "detailSnapshot"->>'isExtend' = 'false');

CREATE UNIQUE INDEX "invoices_gudang_active_unique"
  ON "invoices" ("gudangDokumenId")
  WHERE "deletedAt" IS NULL
    AND "gudangDokumenId" IS NOT NULL
    AND ("detailSnapshot"->>'isExtend' IS NULL OR "detailSnapshot"->>'isExtend' = 'false');