-- Migration: Admin Session Token Blacklist
-- Erlaubt es, Session-Tokens vor Ablauf ungültig zu machen

CREATE TABLE admin_session_blacklist (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  admin_id uuid NOT NULL,
  token_signature text NOT NULL UNIQUE, -- Base64-kodierte Signatur
  revoked_at timestamptz DEFAULT now(),
  reason text NOT NULL, -- "logout", "password_changed", "suspicious_activity"
  notes text
);

CREATE INDEX idx_admin_session_blacklist_sig ON admin_session_blacklist(token_signature);
CREATE INDEX idx_admin_session_blacklist_admin ON admin_session_blacklist(admin_id);
CREATE INDEX idx_admin_session_blacklist_revoked ON admin_session_blacklist(revoked_at DESC);

-- Cleanup: Alte Einträge nach 7 Tagen (nach Token-Ablauf) löschen
CREATE OR REPLACE FUNCTION cleanup_old_blacklist_tokens() RETURNS void AS $$
BEGIN
  DELETE FROM admin_session_blacklist
  WHERE revoked_at < now() - INTERVAL '7 days';
END;
$$ LANGUAGE plpgsql;

-- Trigger: Auto-Cleanup einmal täglich (optional)
-- HINWEIS: In Supabase muss dies manuell via Cron-Funktion aufgerufen werden

---

-- Migration: Action Token Blacklist
-- Verhindert mehrfache Verwendung von Email-Action-Links (Status-Updates)

CREATE TABLE action_token_blacklist (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  anfrage_id uuid NOT NULL,
  token_signature text NOT NULL UNIQUE, -- Base64-kodierte Signatur
  action_type text NOT NULL, -- "bestaetigt", "abgelehnt", "abgeschlossen"
  used_at timestamptz DEFAULT now(),
  used_by_ip text,
  notes text
);

CREATE INDEX idx_action_token_blacklist_sig ON action_token_blacklist(token_signature);
CREATE INDEX idx_action_token_blacklist_anfrage ON action_token_blacklist(anfrage_id);
CREATE INDEX idx_action_token_blacklist_used ON action_token_blacklist(used_at DESC);

-- Cleanup: Alte Einträge nach 14 Tagen löschen (nach Token-Ablauf)
CREATE OR REPLACE FUNCTION cleanup_old_action_tokens() RETURNS void AS $$
BEGIN
  DELETE FROM action_token_blacklist
  WHERE used_at < now() - INTERVAL '14 days';
END;
$$ LANGUAGE plpgsql;

---

-- RLS Policies
ALTER TABLE admin_session_blacklist ENABLE ROW LEVEL SECURITY;
ALTER TABLE action_token_blacklist ENABLE ROW LEVEL SECURITY;

-- Nur Service-Role kann schreiben
CREATE POLICY "Service Role can manage session blacklist" ON admin_session_blacklist
  FOR ALL USING (true) WITH CHECK (false);

CREATE POLICY "Service Role can manage action token blacklist" ON action_token_blacklist
  FOR ALL USING (true) WITH CHECK (false);
