-- name: CreateRefreshToken :one
INSERT INTO refresh_tokens (user_id, token_hash, expires_at)
VALUES ($1, $2, $3)
RETURNING *;

-- name: GetRefreshToken :one
SELECT * FROM refresh_tokens
WHERE token_hash = $1 LIMIT 1;

-- name: GetUserRefreshTokens :many
SELECT * FROM refresh_tokens
WHERE user_id = $1;

-- name: CountUserRefreshTokens :one
SELECT count(*) FROM refresh_tokens
WHERE user_id = $1;

-- name: GetValidRefreshToken :one
SELECT user_id, token_hash
FROM refresh_tokens
WHERE token_hash = $1 
  AND expires_at > NOW()
LIMIT 1;

-- name: DeleteRefreshToken :exec
DELETE FROM refresh_tokens
WHERE token_hash = $1 and user_id = $2;

-- name: DeleteAllUserRefreshTokens :exec
DELETE FROM refresh_tokens
WHERE user_id = $1;

-- name: DeleteOldestRefreshToken :exec
DELETE FROM refresh_tokens
WHERE id = (
    SELECT id
    FROM refresh_tokens rt
    WHERE rt.user_id = $1
    ORDER BY rt.created_at ASC
    LIMIT 1
);
