-- Migration 080: Antrag auf Vereinsgründung (M7)
-- Nutzer verified_pending_club stellt Antrag; Plattform-Admin legt Verein + Abo an.

CREATE TABLE IF NOT EXISTS club_creation_requests (
    id SERIAL PRIMARY KEY,
    profile_id INT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
    proposed_name VARCHAR(200) NOT NULL,
    proposed_abbreviation VARCHAR(50),
    proposed_description TEXT,
    message TEXT,
    status VARCHAR(20) NOT NULL DEFAULT 'pending'
        CHECK (status IN ('pending', 'approved', 'rejected', 'withdrawn')),
    decided_by_profile_id INT REFERENCES profiles(id) ON DELETE SET NULL,
    decided_at TIMESTAMP,
    created_club_id INT REFERENCES clubs(id) ON DELETE SET NULL,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS uq_club_creation_requests_pending
    ON club_creation_requests (profile_id)
    WHERE status = 'pending';

CREATE INDEX IF NOT EXISTS idx_club_creation_requests_status
    ON club_creation_requests (status, created_at);

CREATE INDEX IF NOT EXISTS idx_club_creation_requests_profile
    ON club_creation_requests (profile_id);

DROP TRIGGER IF EXISTS club_creation_requests_update ON club_creation_requests;
CREATE TRIGGER club_creation_requests_update
    BEFORE UPDATE ON club_creation_requests
    FOR EACH ROW EXECUTE FUNCTION update_timestamp();

-- Capabilities (CAPABILITY_CATALOG.v1.md — club.creation_request.*)
INSERT INTO capabilities (id, name, domain, min_account_state, linked_feature_id)
VALUES
    ('club.creation_request.create', 'Vereinsgründung beantragen', 'club', 'verified_pending_club', NULL),
    ('club.creation_request.read_own', 'Eigene Gründungsanträge', 'club', 'verified_pending_club', NULL),
    ('club.creation_request.withdraw', 'Gründungsantrag zurückziehen', 'club', 'verified_pending_club', NULL)
ON CONFLICT (id) DO NOTHING;
