-- name: GetTotalComponentStats :one
SELECT COUNT(DISTINCT ci.component_id) AS total_types, COALESCE(SUM(ci.quantity), 0)::bigint AS total_quantity
FROM component_items ci
JOIN containers con ON ci.container_id = con.id
JOIN shelves s ON con.shelf_id = s.id
JOIN cabinets cab ON s.cabinet_id = cab.id
JOIN rooms r ON cab.room_id = r.id
WHERE sqlc.narg('warehouse_id')::bigint IS NULL OR r.warehouse_id = sqlc.narg('warehouse_id')::bigint;

-- name: CountPendingInvoices :one
SELECT COUNT(*) FROM invoices
WHERE status IN ('draft', 'pending');

-- name: CountLowStockComponents :one
SELECT COUNT(*) FROM components
WHERE total_quantity <= min_quantity;

-- name: GetAbnormalItemCounts :many
SELECT ci.status, COUNT(*) AS count
FROM component_items ci
JOIN containers con ON ci.container_id = con.id
JOIN shelves s ON con.shelf_id = s.id
JOIN cabinets cab ON s.cabinet_id = cab.id
JOIN rooms r ON cab.room_id = r.id
WHERE ci.status != 'normal'
  AND (sqlc.narg('warehouse_id')::bigint IS NULL OR r.warehouse_id = sqlc.narg('warehouse_id')::bigint)
GROUP BY ci.status;

-- name: GetTodayInvoiceCounts :many
SELECT type, COUNT(*) AS count
FROM invoices
WHERE created_at::date = CURRENT_DATE
GROUP BY type;

-- name: GetContainerStats :one
SELECT
  COUNT(*) AS total_containers,
  COUNT(*) - COUNT(DISTINCT ci.container_id) AS empty_containers
FROM containers c
JOIN shelves s ON c.shelf_id = s.id
JOIN cabinets cab ON s.cabinet_id = cab.id
JOIN rooms r ON cab.room_id = r.id
LEFT JOIN component_items ci ON c.id = ci.container_id
WHERE sqlc.narg('warehouse_id')::bigint IS NULL OR r.warehouse_id = sqlc.narg('warehouse_id')::bigint;
