CREATE TABLE IF NOT EXISTS public.process_access (
  process_id    uuid  NOT NULL REFERENCES public.processes(id) ON DELETE CASCADE,
  grantee_type  text  NOT NULL CHECK (grantee_type IN ('user','group')),
  grantee_id    uuid  NOT NULL,
  permission    text  NOT NULL DEFAULT 'view' CHECK (permission IN ('view','edit')),
  PRIMARY KEY (process_id, grantee_type, grantee_id)
);

ALTER TABLE public.process_access ENABLE ROW LEVEL SECURITY;

CREATE POLICY "read_process_access" ON public.process_access
  FOR SELECT USING (auth.uid() IS NOT NULL);

CREATE POLICY "manage_process_access" ON public.process_access
  FOR ALL USING (
    EXISTS (SELECT 1 FROM public.users WHERE id = auth.uid() AND platform_role = 'platform_admin')
    OR EXISTS (
      SELECT 1 FROM public.processes
      WHERE id = process_access.process_id AND owner_id = auth.uid()
    )
  );
