
CREATE TABLE public.qr_posts (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT NOT NULL UNIQUE,
  payload TEXT NOT NULL,
  notes TEXT,
  created_by UUID REFERENCES auth.users(id) ON DELETE SET NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

GRANT SELECT, INSERT, UPDATE, DELETE ON public.qr_posts TO authenticated;
GRANT ALL ON public.qr_posts TO service_role;

ALTER TABLE public.qr_posts ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Authenticated can view qr_posts"
  ON public.qr_posts FOR SELECT TO authenticated USING (true);

CREATE POLICY "Managers can insert qr_posts"
  ON public.qr_posts FOR INSERT TO authenticated
  WITH CHECK (public.has_any_role(auth.uid(), ARRAY['super_admin','company_admin','ops_manager','supervisor']::app_role[]));

CREATE POLICY "Managers can update qr_posts"
  ON public.qr_posts FOR UPDATE TO authenticated
  USING (public.has_any_role(auth.uid(), ARRAY['super_admin','company_admin','ops_manager','supervisor']::app_role[]));

CREATE POLICY "Managers can delete qr_posts"
  ON public.qr_posts FOR DELETE TO authenticated
  USING (public.has_any_role(auth.uid(), ARRAY['super_admin','company_admin','ops_manager','supervisor']::app_role[]));

CREATE TRIGGER tg_qr_posts_updated_at
  BEFORE UPDATE ON public.qr_posts
  FOR EACH ROW EXECUTE FUNCTION public.tg_set_updated_at();
