-- Fix notifications table: add title, message, read columns that server and client expect.
-- The original table only had: id, user_id, type, data (jsonb), is_read, created_at
-- Server inserts use: title, message (and implicitly read=false)
-- Client reads use: title, message, read

ALTER TABLE public.notifications
  ADD COLUMN IF NOT EXISTS title TEXT,
  ADD COLUMN IF NOT EXISTS message TEXT,
  ADD COLUMN IF NOT EXISTS read BOOLEAN DEFAULT false;

-- Backfill read from is_read for any existing rows
UPDATE public.notifications SET read = is_read WHERE read IS NULL;

-- Keep is_read and read in sync
CREATE OR REPLACE FUNCTION public.sync_notification_read()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
  IF TG_OP = 'UPDATE' THEN
    IF NEW.read IS DISTINCT FROM OLD.read THEN
      NEW.is_read := NEW.read;
    ELSIF NEW.is_read IS DISTINCT FROM OLD.is_read THEN
      NEW.read := NEW.is_read;
    END IF;
  END IF;
  RETURN NEW;
END;
$$;

DROP TRIGGER IF EXISTS trg_sync_notification_read ON public.notifications;
CREATE TRIGGER trg_sync_notification_read
  BEFORE UPDATE ON public.notifications
  FOR EACH ROW EXECUTE FUNCTION public.sync_notification_read();
