-- Migration 004: Create auth_sessions table for per-login authentication
--
-- This migration separates user authentication (per-login email verification)
-- from domain verification (one-time DNS check). See ADR-010 for details.
--
-- Key principle: Email code is AUTHENTICATION (every login), never cached.

-- Auth sessions table for temporary per-login authentication state
-- This table stores session data for the authorization flow
CREATE TABLE auth_sessions (
    session_id TEXT PRIMARY KEY,
    me TEXT NOT NULL,
    email TEXT,
    verification_code_hash TEXT,
    code_verified INTEGER NOT NULL DEFAULT 0,
    attempts INTEGER NOT NULL DEFAULT 0,
    client_id TEXT NOT NULL,
    redirect_uri TEXT NOT NULL,
    state TEXT,
    code_challenge TEXT,
    code_challenge_method TEXT,
    scope TEXT,
    response_type TEXT DEFAULT 'id',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    expires_at TIMESTAMP NOT NULL
);

-- Index for expiration-based cleanup
CREATE INDEX idx_auth_sessions_expires ON auth_sessions(expires_at);

-- Index for looking up sessions by domain (for email discovery)
CREATE INDEX idx_auth_sessions_me ON auth_sessions(me);

-- Record this migration
INSERT INTO migrations (version, description) VALUES (4, 'Create auth_sessions table for per-login authentication - separates user authentication from domain verification');
