-- name: CreateServiceSession :one
INSERT INTO service_sessions (
    service_id, client_id, user_id, issued_at, expires_at, last_active,
    ip_address, user_agent, access_token_id, refresh_token_id,
    is_active, scope, claims
) VALUES (
    $1, $2, $3, NOW(), $4, $5,
    $6, $7, $8, $9,
    TRUE, $8, $9
)
RETURNING *;

-- name: ListActiveServiceSessionsByClient :many
SELECT * FROM service_sessions
WHERE client_id = $1
  AND is_active = TRUE
ORDER BY issued_at DESC;

-- name: ListActiveServiceSessionsByUser :many
SELECT * FROM service_sessions
WHERE user_id = $1
  AND is_active = TRUE
ORDER BY issued_at DESC;

-- name: GetServiceSessionByAccessJTI :one
SELECT * FROM service_sessions
WHERE access_token_id = $1
  AND is_active = TRUE;

-- name: GetServiceSessionByRefreshJTI :one
SELECT * FROM service_sessions
WHERE refresh_token_id = $1
  AND is_active = TRUE;

-- name: RevokeServiceSession :exec
UPDATE service_sessions
SET is_active = FALSE,
    revoked_at = NOW()
WHERE id = $1
  AND is_active = TRUE;

-- name: UpdateServiceSessionLastActive :exec
UPDATE service_sessions
SET last_active = NOW()
WHERE id = $1
  AND is_active = TRUE;

-- name: ListAllServiceSessions :many
SELECT * FROM service_sessions
ORDER BY issued_at DESC
LIMIT $1 OFFSET $2;
