-- Wiederkehrende Rechnungen (Abo-Rechnungen)
-- Migration ausführen mit: psql -U pirp_user -d pirp -f tools/migrate_recurring.sql

-- Abo-Vorlagen
CREATE TABLE IF NOT EXISTS recurring_templates (
    id SERIAL PRIMARY KEY,
    template_name VARCHAR(100) NOT NULL,
    customer_id INTEGER NOT NULL REFERENCES customers(id) ON DELETE RESTRICT,
    interval_type VARCHAR(20) NOT NULL CHECK (interval_type IN ('monthly', 'quarterly', 'yearly')),
    start_date DATE NOT NULL,
    end_date DATE,
    next_due_date DATE NOT NULL,
    vat_mode VARCHAR(10) NOT NULL DEFAULT 'klein',
    vat_rate NUMERIC(5,2) NOT NULL DEFAULT 19.00,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    notes_internal TEXT,
    created_at TIMESTAMPTZ DEFAULT now()
);

-- Positionen der Abo-Vorlage
CREATE TABLE IF NOT EXISTS recurring_template_items (
    id SERIAL PRIMARY KEY,
    template_id INTEGER NOT NULL REFERENCES recurring_templates(id) ON DELETE CASCADE,
    position_no INTEGER NOT NULL,
    description TEXT NOT NULL,
    quantity NUMERIC(12,2) NOT NULL DEFAULT 1,
    unit_price NUMERIC(12,2) NOT NULL DEFAULT 0
);

-- Log der generierten Rechnungen
CREATE TABLE IF NOT EXISTS recurring_log (
    id SERIAL PRIMARY KEY,
    template_id INTEGER NOT NULL REFERENCES recurring_templates(id) ON DELETE CASCADE,
    invoice_id INTEGER REFERENCES invoices(id) ON DELETE SET NULL,
    generated_at TIMESTAMPTZ DEFAULT now(),
    due_date DATE NOT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'generated'
);

-- Indices
CREATE INDEX IF NOT EXISTS idx_recurring_next_due ON recurring_templates(next_due_date) WHERE is_active = TRUE;
CREATE INDEX IF NOT EXISTS idx_recurring_log_template ON recurring_log(template_id);
