-- Sprint 7 Phase 1B: Push notification infrastructure
-- Device token registry (Web Push subscriptions + mobile push tokens)

CREATE TABLE device_tokens (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    platform VARCHAR(20) NOT NULL,      -- WEB, IOS, ANDROID
    token TEXT NOT NULL,                 -- Push subscription JSON (Web) or FCM token (mobile)
    device_name VARCHAR(100),            -- e.g. "Chrome on MacBook", "iPhone 15"
    last_used_at TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    tenant_id UUID NOT NULL,
    UNIQUE(user_id, token)
);

CREATE INDEX idx_device_tokens_user ON device_tokens(user_id);
CREATE INDEX idx_device_tokens_platform ON device_tokens(platform, tenant_id);

-- Per-user notification channel preferences
CREATE TABLE notification_preferences (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    channel VARCHAR(20) NOT NULL,       -- IN_APP, EMAIL, WEB_PUSH, MOBILE_PUSH
    enabled BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    tenant_id UUID NOT NULL,
    UNIQUE(user_id, channel)
);

CREATE INDEX idx_notification_preferences_user ON notification_preferences(user_id);
