-- ============================================================================
-- OrbiQuant IA - Trading Platform
-- Schema: auth
-- File: tables/07-password_reset_tokens.sql
-- Description: Password reset tokens and tracking
-- ============================================================================

CREATE TABLE auth.password_reset_tokens (
  -- 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,
  used_at TIMESTAMPTZ,
  is_used 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_password_reset_tokens_user FOREIGN KEY (user_id)
    REFERENCES auth.users(id)
    ON DELETE CASCADE,

  -- Check Constraints
  CONSTRAINT valid_expiration CHECK (expires_at > created_at),
  CONSTRAINT used_consistency CHECK (
    (is_used = true AND used_at IS NOT NULL) OR
    (is_used = false AND used_at IS NULL)
  )
);

-- Indexes for Performance
CREATE INDEX idx_password_reset_tokens_user_id ON auth.password_reset_tokens(user_id);
CREATE INDEX idx_password_reset_tokens_token ON auth.password_reset_tokens(token);
CREATE INDEX idx_password_reset_tokens_email ON auth.password_reset_tokens(email);
CREATE INDEX idx_password_reset_tokens_expires ON auth.password_reset_tokens(expires_at);
CREATE INDEX idx_password_reset_tokens_active ON auth.password_reset_tokens(user_id, is_used, expires_at)
  WHERE is_used = false;

-- Table Comments
COMMENT ON TABLE auth.password_reset_tokens IS 'Password reset tokens for secure password recovery';

-- Column Comments
COMMENT ON COLUMN auth.password_reset_tokens.id IS 'Unique identifier for the reset token';
COMMENT ON COLUMN auth.password_reset_tokens.user_id IS 'Reference to the user account';
COMMENT ON COLUMN auth.password_reset_tokens.email IS 'Email address for password reset';
COMMENT ON COLUMN auth.password_reset_tokens.token IS 'Unique reset token sent to email';
COMMENT ON COLUMN auth.password_reset_tokens.expires_at IS 'Token expiration timestamp';
COMMENT ON COLUMN auth.password_reset_tokens.used_at IS 'Timestamp when token was used';
COMMENT ON COLUMN auth.password_reset_tokens.is_used IS 'Whether the token has been used';
COMMENT ON COLUMN auth.password_reset_tokens.ip_address IS 'IP address when reset was requested';
COMMENT ON COLUMN auth.password_reset_tokens.user_agent IS 'User agent when reset was requested';
COMMENT ON COLUMN auth.password_reset_tokens.created_at IS 'Timestamp when token was created';
