-- Migration: Unique-Constraints für Journal-Einträge
-- Verhindert Doppelbuchungen (max. 1 Journal-Eintrag pro Rechnung/Ausgabe)

-- Zuerst evtl. vorhandene Duplikate bereinigen (behalte nur den neuesten)
DELETE FROM journal_entries a
USING journal_entries b
WHERE a.invoice_id IS NOT NULL
  AND a.invoice_id = b.invoice_id
  AND a.id < b.id;

DELETE FROM journal_entries a
USING journal_entries b
WHERE a.expense_id IS NOT NULL
  AND a.expense_id = b.expense_id
  AND a.id < b.id;

-- Unique-Indexes erstellen
CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_journal_invoice ON journal_entries(invoice_id) WHERE invoice_id IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_journal_expense ON journal_entries(expense_id) WHERE expense_id IS NOT NULL;
