-- n8n import into public.order_groups
--
-- Recommended setup:
-- 1. n8n must call Supabase REST with the SERVICE_ROLE key, not the anon key.
-- 2. Keep RLS closed for anon/authenticated inserts unless the request comes
--    from an authenticated application user with a coordination role.
--
-- n8n HTTP headers for REST inserts:
--   apikey: <SUPABASE_SERVICE_ROLE_KEY>
--   Authorization: Bearer <SUPABASE_SERVICE_ROLE_KEY>
--   Content-Type: application/json
--   Prefer: resolution=merge-duplicates,return=representation
--
-- Endpoint example:
--   POST https://<project-ref>.supabase.co/rest/v1/order_groups
--
-- Why this is needed:
-- current_role_name() is based on auth.uid() and public.users. A plain n8n
-- anon request has no application user, so insert policies such as
-- current_role_name() in ('manager', 'logistician', 'admin') reject the row.
-- service_role bypasses RLS and is the correct key for trusted server workflows.

alter table public.order_groups enable row level security;

drop policy if exists "order groups insert service roles" on public.order_groups;
create policy "order groups insert service roles" on public.order_groups
for insert
with check (public.current_role_name() in ('manager', 'logistician', 'admin'));

-- Optional diagnostic query: if this returns null for the JWT used by n8n,
-- that JWT is not an app user and cannot pass the application-user RLS policy.
select public.current_role_name() as current_app_role;
