-- ============================================================
-- Migration: 003_create_push_tokens
-- Date: 2025-12-19
-- Author: Claude
-- Description: Create table for storing push notification tokens
-- ============================================================

-- UP: Apply migration
-- ============================================================

CREATE TABLE IF NOT EXISTS push_tokens (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id INTEGER REFERENCES person_details(user_id) ON DELETE CASCADE,
    token TEXT NOT NULL,
    platform VARCHAR(20) CHECK (platform IN ('ios', 'android', 'web')),
    device_id TEXT,
    device_name TEXT,
    app_version TEXT,
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    last_used_at TIMESTAMPTZ,

    -- One token per device per user
    UNIQUE(user_id, device_id)
);

-- Indexes for common queries
CREATE INDEX IF NOT EXISTS idx_push_tokens_user ON push_tokens(user_id);
CREATE INDEX IF NOT EXISTS idx_push_tokens_token ON push_tokens(token);
CREATE INDEX IF NOT EXISTS idx_push_tokens_active ON push_tokens(is_active) WHERE is_active = true;

-- Comments
COMMENT ON TABLE push_tokens IS 'Stores push notification tokens for mobile and web clients';
COMMENT ON COLUMN push_tokens.token IS 'Expo Push Token (ExponentPushToken[xxx]) or FCM token';
COMMENT ON COLUMN push_tokens.platform IS 'Device platform: ios, android, or web';
COMMENT ON COLUMN push_tokens.device_id IS 'Unique device identifier';

-- ============================================================
-- DOWN: Rollback migration (for reference only)
-- ============================================================
-- DROP TABLE IF EXISTS push_tokens;
