-- ============================================================================
-- OrbiQuant IA - Trading Platform
-- Schema: auth
-- File: tables/05-email_verifications.sql
-- Description: Email verification tokens and tracking
-- ============================================================================

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

  -- Foreign Key to Users
  user_id UUID NOT NULL,

  -- Email and Token
  email CITEXT NOT NULL,
  token VARCHAR(255) NOT NULL UNIQUE,

  -- Token Lifecycle
  expires_at TIMESTAMPTZ NOT NULL,
  verified_at TIMESTAMPTZ,
  is_verified BOOLEAN NOT NULL DEFAULT false,

  -- Metadata
  ip_address INET,
  user_agent TEXT,

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

  -- Foreign Key Constraints
  CONSTRAINT fk_email_verifications_user FOREIGN KEY (user_id)
    REFERENCES auth.users(id)
    ON DELETE CASCADE,

  -- Check Constraints
  CONSTRAINT valid_expiration CHECK (expires_at > created_at),
  CONSTRAINT verified_consistency CHECK (
    (is_verified = true AND verified_at IS NOT NULL) OR
    (is_verified = false AND verified_at IS NULL)
  )
);

-- Indexes for Performance
CREATE INDEX idx_email_verifications_user_id ON auth.email_verifications(user_id);
CREATE INDEX idx_email_verifications_token ON auth.email_verifications(token);
CREATE INDEX idx_email_verifications_email ON auth.email_verifications(email);
CREATE INDEX idx_email_verifications_expires ON auth.email_verifications(expires_at);
CREATE INDEX idx_email_verifications_pending ON auth.email_verifications(user_id, is_verified, expires_at)
  WHERE is_verified = false;

-- Table Comments
COMMENT ON TABLE auth.email_verifications IS 'Email verification tokens and tracking for user email confirmation';

-- Column Comments
COMMENT ON COLUMN auth.email_verifications.id IS 'Unique identifier for the verification record';
COMMENT ON COLUMN auth.email_verifications.user_id IS 'Reference to the user account';
COMMENT ON COLUMN auth.email_verifications.email IS 'Email address to be verified';
COMMENT ON COLUMN auth.email_verifications.token IS 'Unique verification token sent to email';
COMMENT ON COLUMN auth.email_verifications.expires_at IS 'Token expiration timestamp';
COMMENT ON COLUMN auth.email_verifications.verified_at IS 'Timestamp when email was verified';
COMMENT ON COLUMN auth.email_verifications.is_verified IS 'Whether the email has been verified';
COMMENT ON COLUMN auth.email_verifications.ip_address IS 'IP address when verification was requested';
COMMENT ON COLUMN auth.email_verifications.user_agent IS 'User agent when verification was requested';
COMMENT ON COLUMN auth.email_verifications.created_at IS 'Timestamp when verification was created';
