-- name: GetComponentItemByID :one
SELECT * FROM component_items
WHERE id = sqlc.arg(id);

-- name: ListComponentItems :many
SELECT * FROM component_items
ORDER BY created_at DESC;

-- name: CreateComponentItem :one
INSERT INTO component_items (component_id,container_id,quantity, status, metadata, created_at)
VALUES (
    sqlc.arg(component_id),
    sqlc.arg(container_id),
    sqlc.arg(quantity),
    sqlc.arg(status),
    sqlc.arg(metadata),
    sqlc.arg(created_at)
)
RETURNING *;

-- name: UpdateComponentItem :one
UPDATE component_items
SET component_id = CASE WHEN sqlc.arg(component_id) = '' THEN component_id ELSE sqlc.arg(component_id) END,
    container_id = CASE WHEN sqlc.arg(container_id) = '' THEN container_id ELSE sqlc.arg(container_id) END,
    metadata = coalesce(sqlc.arg(metadata), metadata),
    updated_at = sqlc.arg(updated_at)
WHERE id = sqlc.arg(id)
RETURNING *;

-- name: DeleteComponentItem :execrows
DELETE FROM component_items
WHERE id = $1;

-- name: UpdateComponentItemStatus :one
UPDATE component_items
SET status = sqlc.arg(status),
    updated_at = sqlc.arg(updated_at)
WHERE id = sqlc.arg(id)
RETURNING *;

-- name: UpdateComponentItemQuantity :one
UPDATE component_items
SET quantity = sqlc.arg(quantity),
    updated_at = sqlc.arg(updated_at)
WHERE id = sqlc.arg(id)
RETURNING *;

-- name: GetComponentItemByComponentContainerStatus :one
SELECT * FROM component_items
WHERE component_id = sqlc.arg(component_id)
  AND container_id = sqlc.arg(container_id)
  AND status = sqlc.arg(status);

-- name: FindComponentItem :many
SELECT
    c.name AS component_name,
    ct.name AS type_name,
    ci.quantity,
    ci.status,
    cn.name AS container_name,
    cn.container_type,
    s.name AS shelf_name,
    cb.name AS cabinet_name,
    r.name AS room_name,
    w.name AS warehouse_name
FROM component_items ci
JOIN components c ON ci.component_id = c.id
JOIN component_types ct ON c.component_type_id = ct.id
JOIN containers cn ON ci.container_id = cn.id
JOIN shelves s ON cn.shelf_id = s.id
JOIN cabinets cb ON s.cabinet_id = cb.id
JOIN rooms r ON cb.room_id = r.id
JOIN warehouses w ON r.warehouse_id = w.id
WHERE ci.component_id = sqlc.arg(componentId) AND ci.quantity > 0;

