-- Migration: Storno-Rechnungen + Mahnungen
-- Anwendung: psql -U pirp_user -d pirp -f tools/migrate_storno_mahnung.sql

-- Storno: zwei neue Spalten in invoices
ALTER TABLE invoices
    ADD COLUMN IF NOT EXISTS storno_of INTEGER REFERENCES invoices(id) ON DELETE SET NULL,
    ADD COLUMN IF NOT EXISTS is_storno BOOLEAN NOT NULL DEFAULT FALSE;

-- Mahnungen: neue Tabelle
CREATE TABLE IF NOT EXISTS mahnungen (
    id SERIAL PRIMARY KEY,
    invoice_id INTEGER NOT NULL REFERENCES invoices(id) ON DELETE CASCADE,
    mahnung_date DATE NOT NULL,
    level INTEGER NOT NULL DEFAULT 1 CHECK (level IN (1,2,3)),
    fee_amount NUMERIC(12,2) NOT NULL DEFAULT 0,
    pdf_path TEXT,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_mahnungen_invoice_id ON mahnungen(invoice_id);
