-- Sprint 8: Treasury / Finance tables
-- Fee schedules (Beitragsordnung)
CREATE TABLE fee_schedules (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    club_id UUID NOT NULL REFERENCES clubs(id),
    tenant_id UUID NOT NULL,
    name VARCHAR(100) NOT NULL,
    amount_cents INTEGER NOT NULL,
    interval VARCHAR(20) NOT NULL,
    is_default BOOLEAN DEFAULT FALSE,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

-- Member fee assignment
CREATE TABLE member_fee_assignments (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    member_id UUID NOT NULL REFERENCES members(id),
    club_id UUID NOT NULL REFERENCES clubs(id),
    tenant_id UUID NOT NULL,
    fee_schedule_id UUID NOT NULL REFERENCES fee_schedules(id),
    valid_from DATE NOT NULL,
    valid_to DATE,
    created_at TIMESTAMP DEFAULT NOW(),
    UNIQUE(member_id, valid_from)
);

-- Payments (Zahlungen)
CREATE TABLE payments (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    club_id UUID NOT NULL REFERENCES clubs(id),
    tenant_id UUID NOT NULL,
    member_id UUID NOT NULL REFERENCES members(id),
    amount_cents INTEGER NOT NULL,
    payment_method VARCHAR(30) NOT NULL,
    status VARCHAR(20) NOT NULL DEFAULT 'PAID',
    period_from DATE NOT NULL,
    period_to DATE NOT NULL,
    reference VARCHAR(200),
    notes TEXT,
    recorded_by UUID NOT NULL REFERENCES users(id),
    paid_at TIMESTAMP NOT NULL,
    voided_at TIMESTAMP,
    voided_by UUID REFERENCES users(id),
    void_reason TEXT,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Kassenbuch (cash book / ledger entries) — append-only per §147 AO
CREATE TABLE ledger_entries (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    club_id UUID NOT NULL REFERENCES clubs(id),
    tenant_id UUID NOT NULL,
    transaction_type VARCHAR(10) NOT NULL,
    category VARCHAR(50) NOT NULL,
    amount_cents INTEGER NOT NULL,
    description VARCHAR(500) NOT NULL,
    reference VARCHAR(200),
    payment_id UUID REFERENCES payments(id),
    recorded_by UUID NOT NULL REFERENCES users(id),
    transaction_date DATE NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Indexes
CREATE INDEX idx_fee_schedules_club ON fee_schedules(club_id);
CREATE INDEX idx_fee_schedules_tenant ON fee_schedules(tenant_id);
CREATE INDEX idx_member_fee_assignments_member ON member_fee_assignments(member_id);
CREATE INDEX idx_member_fee_assignments_tenant ON member_fee_assignments(tenant_id);
CREATE INDEX idx_payments_club_member ON payments(club_id, member_id);
CREATE INDEX idx_payments_status ON payments(club_id, status);
CREATE INDEX idx_payments_period ON payments(club_id, period_from, period_to);
CREATE INDEX idx_payments_tenant ON payments(tenant_id);
CREATE INDEX idx_ledger_entries_club_date ON ledger_entries(club_id, transaction_date);
CREATE INDEX idx_ledger_entries_category ON ledger_entries(club_id, category);
CREATE INDEX idx_ledger_entries_tenant ON ledger_entries(tenant_id);
