-- ============================================================================
-- OrbiQuant IA - Trading Platform
-- Schema: auth
-- File: tables/12-user_push_tokens.sql
-- Description: User push notification tokens for FCM/APNs/Web Push
-- ============================================================================

CREATE TABLE auth.user_push_tokens (
  -- Primary Key
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Foreign Key to Users
  user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,

  -- Token Information
  token TEXT NOT NULL,
  platform VARCHAR(20) NOT NULL,

  -- Device Information
  device_info JSONB,

  -- Status
  is_active BOOLEAN NOT NULL DEFAULT TRUE,
  last_used_at TIMESTAMPTZ,

  -- Audit
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

  -- Constraints
  CONSTRAINT valid_platform CHECK (platform IN ('web', 'ios', 'android')),
  CONSTRAINT unique_token UNIQUE (token)
);

-- Indexes for Performance
CREATE INDEX idx_push_tokens_user ON auth.user_push_tokens(user_id) WHERE is_active = TRUE;
CREATE INDEX idx_push_tokens_platform ON auth.user_push_tokens(platform);

-- Table Comments
COMMENT ON TABLE auth.user_push_tokens IS 'Push notification tokens for FCM, APNs, and Web Push';

-- Column Comments
COMMENT ON COLUMN auth.user_push_tokens.id IS 'Unique identifier for the token record';
COMMENT ON COLUMN auth.user_push_tokens.user_id IS 'Reference to the user owning this token';
COMMENT ON COLUMN auth.user_push_tokens.token IS 'The push notification token string';
COMMENT ON COLUMN auth.user_push_tokens.platform IS 'Platform type (web, ios, android)';
COMMENT ON COLUMN auth.user_push_tokens.device_info IS 'Device metadata as JSON (model, os_version, app_version, etc.)';
COMMENT ON COLUMN auth.user_push_tokens.is_active IS 'Whether the token is currently valid';
COMMENT ON COLUMN auth.user_push_tokens.last_used_at IS 'Timestamp of last successful notification sent';
COMMENT ON COLUMN auth.user_push_tokens.created_at IS 'Timestamp when token was registered';
COMMENT ON COLUMN auth.user_push_tokens.updated_at IS 'Timestamp when token was last updated';
