-- name: CreateNote :one
INSERT INTO notes (user_id)
VALUES ($1)
RETURNING *;

-- name: ListNotes :many
SELECT 
    n.id AS note_id,
    n.user_id AS owner_id,
    nv.title,
    n.expires_at,
    n.updated_at
FROM notes n
JOIN note_versions nv 
    ON n.id = nv.note_id AND n.current_version = nv.version_number
WHERE n.user_id = $1
ORDER BY n.updated_at DESC
LIMIT $2 OFFSET $3;

-- name: GetFullNote :one
SELECT 
    n.id AS note_id,
    n.user_id AS owner_id,
    nv.title, 
    nv.content, 
    nv.version_number, 
    nv.created_at AS version_created_at,
    n.expires_at AS note_expires_at,
    n.created_at AS note_created_at,
    n.updated_at AS note_updated_at
FROM notes n
JOIN note_versions nv 
    ON n.id = nv.note_id AND n.current_version = nv.version_number
WHERE n.id = $1;

-- name: DeleteNote :exec
DELETE FROM notes
WHERE id = $1 AND user_id = $2;

-- name: SetNoteExpiration :exec
UPDATE notes 
SET expires_at = $1, updated_at = NOW() 
WHERE id = $2 AND user_id = $3;

-- name: ListExpiredNotes :many
SELECT 
    n.id AS note_id,
    n.user_id AS owner_id,
    nv.title,
    n.expires_at
FROM notes n
JOIN note_versions nv 
    ON n.id = nv.note_id AND n.current_version = nv.version_number
WHERE n.expires_at <= NOW()
ORDER BY n.expires_at;

-- name: DeleteExpiredNotes :exec
DELETE FROM notes
WHERE expires_at < NOW();
