-- Run this in Supabase SQL Editor if you get "permission denied for table profiles"
-- 1) Grants the Supabase API roles access to the omotomo schema and profiles table.
-- 2) Ensures RLS policies exist on omotomo.profiles (skip policy creation if you already have them).

-- Allow anon and authenticated roles to use the omotomo schema
GRANT USAGE ON SCHEMA omotomo TO anon, authenticated;

-- Allow reading and writing profiles (RLS policies control which rows)
GRANT SELECT, INSERT, UPDATE, DELETE ON omotomo.profiles TO anon, authenticated;

-- RLS: ensure the table is protected and policies allow the right access
ALTER TABLE omotomo.profiles ENABLE ROW LEVEL SECURITY;

-- Drop existing policies if you need to recreate (optional; remove the DROP lines if policies already work)
DROP POLICY IF EXISTS profiles_select ON omotomo.profiles;
DROP POLICY IF EXISTS profiles_insert ON omotomo.profiles;
DROP POLICY IF EXISTS profiles_update ON omotomo.profiles;
DROP POLICY IF EXISTS profiles_delete ON omotomo.profiles;

-- Anyone can read profiles (e.g. show creator names on community decks)
CREATE POLICY profiles_select ON omotomo.profiles FOR SELECT USING (true);

-- Users can insert/update/delete only their own profile (id = auth.uid())
CREATE POLICY profiles_insert ON omotomo.profiles FOR INSERT WITH CHECK (auth.uid() = id);
CREATE POLICY profiles_update ON omotomo.profiles FOR UPDATE USING (auth.uid() = id) WITH CHECK (auth.uid() = id);
CREATE POLICY profiles_delete ON omotomo.profiles FOR DELETE USING (auth.uid() = id);
