
CREATE TABLE IF NOT EXISTS public.error_logs (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id uuid,
  message text NOT NULL,
  stack text,
  component_stack text,
  url text,
  user_agent text,
  severity text NOT NULL DEFAULT 'error',
  context jsonb DEFAULT '{}'::jsonb,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_error_logs_created_at ON public.error_logs (created_at DESC);
CREATE INDEX IF NOT EXISTS idx_error_logs_severity ON public.error_logs (severity);

ALTER TABLE public.error_logs ENABLE ROW LEVEL SECURITY;

CREATE POLICY "anyone_can_insert_error_logs"
  ON public.error_logs FOR INSERT
  WITH CHECK (true);

CREATE POLICY "admins_can_view_error_logs"
  ON public.error_logs FOR SELECT
  USING (public.is_admin(auth.uid()));
