-- name: CreateNoteVersion :exec
WITH potential_duplicate AS (
    SELECT version_number
    FROM note_versions
    WHERE
        note_id = $1
        AND content_hash = $2
    ORDER BY version_number DESC
    LIMIT 1
),
note_update AS (
    UPDATE notes
    SET
        current_version = COALESCE(
            (SELECT version_number FROM potential_duplicate),
            latest_version + 1 -- increment only if we don't jump into a historical version
        ),
        latest_version = CASE
            WHEN (SELECT version_number FROM potential_duplicate) IS NULL
            THEN latest_version + 1
            ELSE latest_version
        END,
        updated_at = NOW()
    WHERE id = $1
    RETURNING current_version, latest_version
)
INSERT INTO note_versions (
    note_id, title, content, version_number, content_hash
)
SELECT
    $1, -- note_id
    $3, -- title
    $4, -- content
    current_version,
    $2 -- content_hash
FROM note_update
WHERE NOT EXISTS (SELECT 1 FROM potential_duplicate);

-- name: GetVersionHistory :many
SELECT 
    id AS version_id,
    title,
    version_number,
    created_at
FROM note_versions
WHERE note_id = $1
ORDER BY version_number DESC
LIMIT $2 OFFSET $3;

-- name: GetVersion :one
SELECT
    id AS version_id,
    title,
    content,
    version_number,
    created_at
FROM note_versions
WHERE note_id = $1 AND id = $2;
