-- Migration: Create user_sessions table (alias for sessions compatibility)
-- Description: Alternative sessions table for legacy compatibility

-- This is actually just a view or alias for the sessions table
-- The sessions table already exists and serves this purpose

-- If we really need a separate user_sessions table:
CREATE TABLE IF NOT EXISTS user_sessions (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL,
    session_token VARCHAR(255) NOT NULL,
    ip_address VARCHAR(45),
    user_agent TEXT,
    is_active BOOLEAN DEFAULT true,
    last_activity TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
    revoked_at TIMESTAMP WITH TIME ZONE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    
    CONSTRAINT fk_user_sessions_user_id FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

-- Indexes
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_sessions_token ON user_sessions(session_token);
CREATE INDEX IF NOT EXISTS idx_user_sessions_user_id ON user_sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_user_sessions_is_active ON user_sessions(is_active) WHERE is_active = true;
CREATE INDEX IF NOT EXISTS idx_user_sessions_expires_at ON user_sessions(expires_at);
CREATE INDEX IF NOT EXISTS idx_user_sessions_last_activity ON user_sessions(last_activity DESC);

-- Comments
COMMENT ON TABLE user_sessions IS 'User sessions for authentication tracking (alternative to sessions table)';
COMMENT ON COLUMN user_sessions.session_token IS 'Unique session token (hashed)';
COMMENT ON COLUMN user_sessions.revoked_at IS 'Timestamp when session was revoked';
COMMENT ON COLUMN user_sessions.last_activity IS 'Last activity timestamp (updated periodically with debounce)';

