Jeder Darf unangemeldet:

-- 1. Sicherstellen, dass RLS aktiv ist
ALTER TABLE todos ENABLE ROW LEVEL SECURITY;

-- 2. Alle alten Policies für 'todos' löschen, um sauber zu starten
DROP POLICY IF EXISTS "Enable all access for all users" ON todos;
DROP POLICY IF EXISTS "Public Access" ON todos;

-- 3. Eine neue, wasserdichte Policy für anonyme Nutzer erstellen
CREATE POLICY "Allow anonymous all" 
ON todos FOR ALL 
TO anon 
USING (true) 
WITH CHECK (true);

-- 4. Berechtigungen auf Tabellenebene vergeben (WICHTIG!)
GRANT ALL ON TABLE todos TO anon;
GRANT ALL ON TABLE todos TO authenticated;
GRANT ALL ON TABLE todos TO postgres;
GRANT ALL ON TABLE todos TO service_role;

-- 5. Auch für die Sequence (falls vorhanden, für IDs)
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO anon;

alle authentisierten Leute dürfen:

-- 1. Sicherstellen, dass RLS weiterhin aktiv ist
ALTER TABLE todos ENABLE ROW LEVEL SECURITY;

-- 2. Die alte 'Allow anonymous all' Policy löschen
DROP POLICY IF EXISTS "Allow anonymous all" ON todos;

-- 3. Neue Policies für authentifizierte Benutzer erstellen
-- Diese Policy erlaubt allen authentifizierten Benutzern Lese- und Schreibzugriffe auf die Tabelle.
CREATE POLICY "Allow authenticated users all" 
ON todos FOR ALL 
TO authenticated 
USING (true) 
WITH CHECK (true);

-- 4. Berechtigungen anpassen (WICHTIG!)
-- Wir entziehen der Rolle 'anon' die Rechte und belassen sie bei 'authenticated' und dem System.
REVOKE ALL ON TABLE todos FROM anon;
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE todos TO authenticated;
GRANT ALL ON TABLE todos TO postgres;
GRANT ALL ON TABLE todos TO service_role;

-- 5. Sequences für authentifizierte Nutzer freigeben (falls IDs generiert werden)
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO authenticated;