-- Error / crash tracking. Captures both client-side React errors (via the
-- error boundaries that POST to /api/errors) and server-side failures (via
-- logError() in src/lib/error-log.ts). Surfaced in the admin panel at
-- /admin/errors so production bugs are visible instead of silent.
CREATE TABLE IF NOT EXISTS error_events (
  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  level       varchar(20)  NOT NULL DEFAULT 'error',   -- error | warn | fatal
  source      varchar(20)  NOT NULL DEFAULT 'client',  -- client | server
  message     text         NOT NULL,
  stack       text,
  url         text,                                    -- route / pathname where it happened
  digest      varchar(120),                            -- Next.js error digest (server)
  user_id     uuid,
  family_id   uuid,
  user_agent  text,
  metadata    jsonb DEFAULT '{}',
  created_at  timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_error_events_created ON error_events (created_at DESC);
CREATE INDEX IF NOT EXISTS idx_error_events_source  ON error_events (source);
CREATE INDEX IF NOT EXISTS idx_error_events_message ON error_events (message);
