-- name: GetDocument :one
SELECT * FROM documents WHERE id = ?;

-- name: ListDocuments :many
SELECT * FROM documents ORDER BY created DESC LIMIT ? OFFSET ?;

-- name: ListDocumentsByType :many
SELECT * FROM documents WHERE type = ? ORDER BY created DESC LIMIT ? OFFSET ?;

-- name: CreateDocument :execresult
INSERT INTO documents (
    type, created, user_id, doc_page_count, cmc_reference, 
    pdf_filename, pdf_created_at, pdf_created_by_user_id, 
    shipping_details, revision, bill_to, ship_to, 
    email_sent_at, email_sent_by_user_id
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);

-- name: UpdateDocument :exec
UPDATE documents SET 
    type = ?, user_id = ?, doc_page_count = ?, cmc_reference = ?, 
    pdf_filename = ?, pdf_created_at = ?, pdf_created_by_user_id = ?, 
    shipping_details = ?, revision = ?, bill_to = ?, ship_to = ?, 
    email_sent_at = ?, email_sent_by_user_id = ?
WHERE id = ?;

-- name: DeleteDocument :exec
DELETE FROM documents WHERE id = ?;

-- name: GetRecentDocuments :many
SELECT 
    d.id,
    d.type,
    d.created,
    d.cmc_reference,
    d.pdf_filename,
    d.revision,
    u.username as created_by_username,
    CASE 
        WHEN d.type = 'quote' THEN CONCAT('Quote ', d.cmc_reference)
        WHEN d.type = 'invoice' THEN CONCAT('Invoice ', d.cmc_reference)
        WHEN d.type = 'purchaseOrder' THEN CONCAT('Purchase Order ', d.cmc_reference)
        WHEN d.type = 'orderAck' THEN CONCAT('Order Ack ', d.cmc_reference)
        WHEN d.type = 'packingList' THEN CONCAT('Packing List ', d.cmc_reference)
        ELSE CONCAT(d.type, ' ', d.cmc_reference)
    END as display_name
FROM documents d
LEFT JOIN users u ON d.user_id = u.id
ORDER BY d.created DESC
LIMIT ?;

-- name: CountDocuments :one
SELECT COUNT(*) FROM documents;

-- name: CountDocumentsByType :one
SELECT COUNT(*) FROM documents WHERE type = ?;

-- name: GetDocumentWithUser :one
SELECT 
    d.id,
    d.type,
    d.created,
    d.user_id,
    d.doc_page_count,
    d.cmc_reference,
    d.pdf_filename,
    d.pdf_created_at,
    d.pdf_created_by_user_id,
    d.shipping_details,
    d.revision,
    d.bill_to,
    d.ship_to,
    d.email_sent_at,
    d.email_sent_by_user_id,
    u.username as user_username,
    u.first_name as user_first_name,
    u.last_name as user_last_name,
    u.email as user_email,
    pu.username as pdf_creator_username,
    pu.first_name as pdf_creator_first_name,
    pu.last_name as pdf_creator_last_name,
    pu.email as pdf_creator_email
FROM documents d
LEFT JOIN users u ON d.user_id = u.id
LEFT JOIN users pu ON d.pdf_created_by_user_id = pu.id
WHERE d.id = ?;