-- Migration: Create notifications table v2 - uses UUID v7
-- Description: Stores user notifications for in-app and push notifications

CREATE TABLE IF NOT EXISTS notifications_v2 (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v7(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    tenant_id UUID,
    
    -- Notification content
    title VARCHAR(255) NOT NULL,
    message TEXT NOT NULL,
    type VARCHAR(50) NOT NULL DEFAULT 'info',
    
    -- Action/Link
    action_url VARCHAR(500),
    action_label VARCHAR(100),
    
    -- Status
    read BOOLEAN DEFAULT false,
    read_at TIMESTAMP,
    
    -- Push notification
    push_sent BOOLEAN DEFAULT false,
    push_sent_at TIMESTAMP,
    
    -- Metadata
    metadata JSONB,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- FCM device tokens for push notifications (v2 with UUID v7)
CREATE TABLE IF NOT EXISTS fcm_tokens_v2 (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v7(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    token VARCHAR(500) NOT NULL,
    device_type VARCHAR(20),
    device_name VARCHAR(100),
    active BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(user_id, token)
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_notifications_v2_user ON notifications_v2(user_id);
CREATE INDEX IF NOT EXISTS idx_notifications_v2_tenant ON notifications_v2(tenant_id);
CREATE INDEX IF NOT EXISTS idx_notifications_v2_read ON notifications_v2(user_id, read);
CREATE INDEX IF NOT EXISTS idx_notifications_v2_type ON notifications_v2(type);
CREATE INDEX IF NOT EXISTS idx_notifications_v2_created ON notifications_v2(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_fcm_tokens_v2_user ON fcm_tokens_v2(user_id);
CREATE INDEX IF NOT EXISTS idx_fcm_tokens_v2_active ON fcm_tokens_v2(user_id, active);

COMMENT ON TABLE notifications_v2 IS 'User notifications for in-app display and push notifications';
COMMENT ON TABLE fcm_tokens_v2 IS 'Firebase Cloud Messaging device tokens for push notifications';
