DROP TABLE IF EXISTS public.todos;
CREATE TABLE public.todos (
  id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
  title text NOT NULL,
  completed boolean DEFAULT false,
  user_id uuid, -- For RLS testing later
  created_at timestamptz DEFAULT now()
);

ALTER TABLE public.todos ENABLE ROW LEVEL SECURITY;

-- Grants for public
GRANT ALL ON public.todos TO anon, authenticated;

-- Grants for Realtime schema
GRANT USAGE ON SCHEMA madbase_realtime TO anon, authenticated;
GRANT ALL ON ALL TABLES IN SCHEMA madbase_realtime TO anon, authenticated;
GRANT ALL ON ALL SEQUENCES IN SCHEMA madbase_realtime TO anon, authenticated;
GRANT ALL ON ALL FUNCTIONS IN SCHEMA madbase_realtime TO anon, authenticated;

-- Allow everything for anon for now to test basic CRUD
CREATE POLICY "Allow anon select" ON public.todos FOR SELECT TO anon USING (true);
CREATE POLICY "Allow anon insert" ON public.todos FOR INSERT TO anon WITH CHECK (true);
CREATE POLICY "Allow anon update" ON public.todos FOR UPDATE TO anon USING (true);
CREATE POLICY "Allow anon delete" ON public.todos FOR DELETE TO anon USING (true);

-- Allow authenticated users
CREATE POLICY "Allow auth select" ON public.todos FOR SELECT TO authenticated USING (true);
CREATE POLICY "Allow auth insert" ON public.todos FOR INSERT TO authenticated WITH CHECK (true);
CREATE POLICY "Allow auth update" ON public.todos FOR UPDATE TO authenticated USING (true);
CREATE POLICY "Allow auth delete" ON public.todos FOR DELETE TO authenticated USING (true);

-- Enable Realtime
CREATE TRIGGER realtime_todos
AFTER INSERT OR UPDATE OR DELETE ON public.todos
FOR EACH ROW EXECUTE FUNCTION madbase_realtime.broadcast_changes();

-- Storage Setup
INSERT INTO storage.buckets (id, name, public) VALUES ('test-bucket', 'test-bucket', true) ON CONFLICT DO NOTHING;
INSERT INTO storage.buckets (id, name, public) VALUES ('public-bucket', 'public-bucket', true) ON CONFLICT DO NOTHING;
INSERT INTO storage.buckets (id, name, public) VALUES ('private-bucket', 'private-bucket', false) ON CONFLICT DO NOTHING;

-- Allow anon to upload to test-bucket and public-bucket
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT FROM pg_policies WHERE tablename = 'objects' AND policyname = 'Anon can insert into public buckets'
  ) THEN
    CREATE POLICY "Anon can insert into public buckets" 
    ON storage.objects FOR INSERT 
    TO anon 
    WITH CHECK ( bucket_id IN ('test-bucket', 'public-bucket') );
  END IF;
END
$$;
