-- =============================================================================
-- Freemium F3c — root_redirect (pra onde o visitante não-logado vai na raiz "/")
--
-- ⚠️ APLICAR COMO supabase_admin (RLS por is_saas_admin).
--
-- Config singleton saas_app_config + RPC pública get_root_redirect() (anon lê o
-- alvo: 'landing' | 'login'). O guard do front usa pra rotear "/". Só saas_admin
-- altera (via UPDATE direto, gated por RLS).
-- =============================================================================

BEGIN;

CREATE TABLE IF NOT EXISTS public.saas_app_config (
    id            boolean PRIMARY KEY DEFAULT true,   -- singleton: sempre id=true
    root_redirect text NOT NULL DEFAULT 'landing' CHECK (root_redirect IN ('landing','login')),
    updated_at    timestamptz NOT NULL DEFAULT now(),
    updated_by    uuid,
    CONSTRAINT saas_app_config_singleton CHECK (id)
);

INSERT INTO public.saas_app_config (id) VALUES (true) ON CONFLICT (id) DO NOTHING;

ALTER TABLE public.saas_app_config ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS saas_app_config_read ON public.saas_app_config;
CREATE POLICY saas_app_config_read ON public.saas_app_config FOR SELECT USING (true);
DROP POLICY IF EXISTS saas_app_config_write ON public.saas_app_config;
CREATE POLICY saas_app_config_write ON public.saas_app_config
    FOR UPDATE USING (public.is_saas_admin()) WITH CHECK (public.is_saas_admin());

GRANT SELECT ON public.saas_app_config TO anon, authenticated;
GRANT UPDATE ON public.saas_app_config TO authenticated;

-- RPC pública: alvo do "/" pra visitante não-logado
CREATE OR REPLACE FUNCTION public.get_root_redirect()
RETURNS text LANGUAGE sql STABLE SECURITY DEFINER SET search_path TO 'public','pg_temp'
AS $$
    SELECT COALESCE((SELECT root_redirect FROM public.saas_app_config WHERE id), 'landing');
$$;
ALTER FUNCTION public.get_root_redirect() OWNER TO supabase_admin;
REVOKE ALL ON FUNCTION public.get_root_redirect() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.get_root_redirect() TO anon, authenticated, service_role;

COMMIT;
