-- Migration 082: Plattform-/Profil-Ausnahmen vom Vereins-Kontingent (M5+)
-- Superadmin & konfigurierbare Rollen/Profile verbrauchen kein club_feature_usage.

CREATE TABLE IF NOT EXISTS platform_role_club_feature_exemptions (
    id              SERIAL PRIMARY KEY,
    portal_role     TEXT NOT NULL,
    feature_id      TEXT REFERENCES features(id) ON DELETE CASCADE,
    note            TEXT,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS uq_platform_role_club_feat_exempt
    ON platform_role_club_feature_exemptions (portal_role, COALESCE(feature_id, '*'));

CREATE TABLE IF NOT EXISTS profile_club_feature_exemptions (
    id                  SERIAL PRIMARY KEY,
    profile_id          INT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
    feature_id          TEXT REFERENCES features(id) ON DELETE CASCADE,
    reason              TEXT,
    set_by_profile_id   INT REFERENCES profiles(id) ON DELETE SET NULL,
    created_at          TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS uq_profile_club_feat_exempt
    ON profile_club_feature_exemptions (profile_id, COALESCE(feature_id, '*'));

CREATE INDEX IF NOT EXISTS idx_profile_club_feat_exempt_profile
    ON profile_club_feature_exemptions (profile_id);

-- Superadmin: alle Vereins-Features ohne Kontingent-Verbrauch
INSERT INTO platform_role_club_feature_exemptions (portal_role, feature_id, note)
SELECT 'superadmin', NULL, 'Plattform-Administrator: kein Vereins-Kontingent'
WHERE NOT EXISTS (
    SELECT 1 FROM platform_role_club_feature_exemptions
    WHERE portal_role = 'superadmin' AND feature_id IS NULL
);
