-- Store one recipient's reference to a delivered invitation event. The -- unique key absorbs at-least-once redelivery without copying event content. -- name: InsertNotificationInboxEvent :execrows INSERT INTO notification_inbox_events ( recipient_user_id, event_id, organization_id, event_type, schema_version, source_type, source_id, occurred_at ) VALUES ( sqlc.arg(recipient_user_id), sqlc.arg(event_id), sqlc.arg(organization_id), sqlc.arg(event_type), sqlc.arg(schema_version), sqlc.arg(source_type), sqlc.arg(source_id), sqlc.arg(occurred_at) ) ON CONFLICT (recipient_user_id, event_id) DO NOTHING; -- Read the existing row after a duplicate insert so the repository can reject -- an event ID whose immutable metadata changed on redelivery. -- name: GetNotificationInboxEvent :one SELECT recipient_user_id, event_id, organization_id, event_type, schema_version, source_type, source_id, occurred_at, read_at FROM notification_inbox_events WHERE recipient_user_id = sqlc.arg(recipient_user_id) AND event_id = sqlc.arg(event_id); -- List only the authenticated recipient's rows, optionally narrowed to one -- organization context. The caller resolves current source visibility before -- returning content. -- name: ListNotificationInboxEvents :many SELECT recipient_user_id, event_id, organization_id, event_type, schema_version, source_type, source_id, occurred_at, read_at FROM notification_inbox_events WHERE recipient_user_id = sqlc.arg(recipient_user_id) AND ( sqlc.narg(organization_id)::uuid IS NULL OR organization_id = sqlc.narg(organization_id)::uuid ) AND ( sqlc.narg(after_occurred_at)::timestamptz IS NULL OR (occurred_at, event_id) < ( sqlc.narg(after_occurred_at)::timestamptz, sqlc.narg(after_event_id)::uuid ) ) ORDER BY occurred_at DESC, event_id DESC LIMIT sqlc.arg(page_limit); -- Persist the first read time under exact recipient and organization scope. -- Repeated calls preserve the original read timestamp. -- name: MarkNotificationInboxEventRead :one UPDATE notification_inbox_events SET read_at = COALESCE(read_at, sqlc.arg(read_at)::timestamptz) WHERE recipient_user_id = sqlc.arg(recipient_user_id) AND organization_id = sqlc.arg(organization_id) AND event_id = sqlc.arg(event_id) RETURNING recipient_user_id, event_id, organization_id, event_type, schema_version, source_type, source_id, occurred_at, read_at;