-- name: GetLineItem :one
SELECT * FROM line_items
WHERE id = ? LIMIT 1;

-- name: ListLineItems :many
SELECT * FROM line_items
ORDER BY item_number ASC
LIMIT ? OFFSET ?;

-- name: ListLineItemsByDocument :many
SELECT * FROM line_items
WHERE document_id = ?
ORDER BY item_number ASC;

-- name: CreateLineItem :execresult
INSERT INTO line_items (
    item_number, `option`, quantity, title, description, 
    document_id, product_id, has_text_prices, has_price,
    unit_price_string, gross_price_string, costing_id,
    gross_unit_price, net_unit_price, discount_percent,
    discount_amount_unit, discount_amount_total, 
    gross_price, net_price
) VALUES (
    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
);

-- name: UpdateLineItem :exec
UPDATE line_items
SET item_number = ?,
    `option` = ?,
    quantity = ?,
    title = ?,
    description = ?,
    document_id = ?,
    product_id = ?,
    has_text_prices = ?,
    has_price = ?,
    unit_price_string = ?,
    gross_price_string = ?,
    costing_id = ?,
    gross_unit_price = ?,
    net_unit_price = ?,
    discount_percent = ?,
    discount_amount_unit = ?,
    discount_amount_total = ?,
    gross_price = ?,
    net_price = ?
WHERE id = ?;

-- name: DeleteLineItem :exec
DELETE FROM line_items
WHERE id = ?;

-- name: GetLineItemsTable :many
SELECT li.*, p.title as product_title, p.model_number
FROM line_items li
LEFT JOIN products p ON li.product_id = p.id
WHERE li.document_id = ?
ORDER BY li.item_number ASC;

-- name: GetLineItemsByProduct :many
SELECT * FROM line_items
WHERE product_id = ?
ORDER BY item_number ASC;

-- name: GetMaxItemNumber :one
SELECT COALESCE(MAX(item_number), 0) as max_item_number 
FROM line_items 
WHERE document_id = ?;

-- name: UpdateLineItemPrices :exec
UPDATE line_items 
SET gross_unit_price = ?,
    net_unit_price = ?,
    gross_price = ?,
    net_price = ?
WHERE id = ?;