-- Migration 020: Create notifications table
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE IF NOT EXISTS notifications (
    id          UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    user_id     UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    typ         VARCHAR(50)  NOT NULL,
    titel       VARCHAR(500) NOT NULL,
    nachricht   TEXT         NOT NULL,
    schwere     VARCHAR(20)  NOT NULL DEFAULT 'info'
                    CHECK (schwere IN ('info', 'warnung', 'fehler')),
    gelesen     BOOLEAN      NOT NULL DEFAULT FALSE,
    gelesen_am  TIMESTAMPTZ,
    link        VARCHAR(500),
    quell_id    VARCHAR(100),
    quell_typ   VARCHAR(50),
    erstellt_am TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

-- Fast lookup for unread badge count
CREATE INDEX IF NOT EXISTS notifications_user_unread_idx
    ON notifications (user_id, gelesen)
    WHERE NOT gelesen;

-- Fast lookup for notification list ordered by date
CREATE INDEX IF NOT EXISTS notifications_user_date_idx
    ON notifications (user_id, erstellt_am DESC);

-- Dedup index: one unread notification per (user, source type, source id)
CREATE UNIQUE INDEX IF NOT EXISTS notifications_dedup_idx
    ON notifications (user_id, quell_typ, quell_id)
    WHERE NOT gelesen AND quell_typ IS NOT NULL AND quell_id IS NOT NULL;
