-- name: ApplyLabel :one
INSERT INTO documentLabels (documentId, label, appliedBy)
VALUES ($1, $2, $3)
RETURNING *;

-- name: GetDocumentLabels :many
SELECT * FROM documentLabels
WHERE documentId = $1
ORDER BY appliedAt DESC;

-- name: GetMostRecentLabel :one
SELECT * FROM documentLabels
WHERE documentId = $1 AND label = $2
ORDER BY appliedAt DESC
LIMIT 1;

-- name: GetDocumentsByLabel :many
SELECT DISTINCT d.*
FROM documents d
INNER JOIN documentLabels dl ON d.id = dl.documentId
WHERE d.clientId = $1 AND dl.label = $2
ORDER BY d.id;

-- name: GetDocumentsByLabelAndFolder :many
SELECT DISTINCT d.*
FROM documents d
INNER JOIN documentLabels dl ON d.id = dl.documentId
WHERE d.folderId = $1 AND dl.label = $2
ORDER BY d.id;

-- name: GetAllLabels :many
SELECT * FROM labels
ORDER BY label;

-- name: CreateLabel :one
INSERT INTO labels (label, description)
VALUES ($1, $2)
RETURNING *;

-- name: GetDocumentLabelHistory :many
SELECT dl.*, d.filename
FROM documentLabels dl
INNER JOIN documents d ON dl.documentId = d.id
WHERE d.clientId = $1
ORDER BY dl.appliedAt DESC
LIMIT $2 OFFSET $3;
