-- name: GetSession :one
SELECT * FROM sessions WHERE token = $1;

-- name: GetSessions :many
SELECT * FROM sessions WHERE uid = $1 ORDER BY $2;

-- name: GetActiveSessions :many
SELECT * FROM sessions WHERE uid = $1 AND (expires > CURRENT_TIMESTAMP OR expires IS NULL) ORDER BY $2;

-- name: CreateSession :exec
INSERT INTO sessions (uid, token, last_activity) VALUES ($1, $2, CURRENT_TIMESTAMP);

-- name: QuickUpdateSession :exec
WITH updated_session AS (
    UPDATE sessions 
    SET last_activity = CURRENT_TIMESTAMP 
    WHERE token = $1 
    RETURNING id
)
INSERT INTO session_ips (session_id, ip_address, agent, access_time)
VALUES (
    (SELECT id FROM updated_session), 
    $2, 
    $3,
    CURRENT_TIMESTAMP
)
ON CONFLICT (session_id, ip_address) 
DO UPDATE SET 
    agent = EXCLUDED.agent,
    access_time = CURRENT_TIMESTAMP;

-- name: ExpireSession :exec
UPDATE sessions SET expires = 1 WHERE token = $1;

