-- name: CreateExpense :one
INSERT INTO expenses (project_id, budget_id, amount, expenses_at, expenses_type, remark, status, created_user_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING *;

-- name: UpdateExpense :one
UPDATE expenses
SET
    project_id = COALESCE(sqlc.narg(project_id), project_id),
    budget_id = COALESCE(sqlc.narg(budget_id), budget_id),
    amount = COALESCE(sqlc.narg(amount), amount),
    expenses_at = COALESCE(sqlc.narg(expenses_at), expenses_at),
    expenses_type = COALESCE(sqlc.narg(expenses_type), expenses_type),
    remark = COALESCE(sqlc.narg(remark), remark),
    status = COALESCE(sqlc.narg(status), status),
    updated_user_id = COALESCE(sqlc.narg(updated_user_id), updated_user_id),
    updated_at = NOW()
WHERE id = $1
RETURNING *;

-- name: GetExpense :one
SELECT * 
FROM expenses 
WHERE id = $1
LIMIT 1;

-- name: SumExpense :one
SELECT SUM(amount)::numeric
FROM expenses;

-- name: SumExpenseByProjectID :one
SELECT SUM(amount)::numeric
FROM expenses
WHERE project_id = $1;

-- name: StatisticsExpense :many
SELECT SUM(amount)::numeric as total_amount,
    (select name from categories where id = expenses.expenses_type) expenses_type_name
FROM expenses
GROUP BY expenses_type;

-- name: StatisticsExpenseByProjectID :many
SELECT SUM(amount)::numeric as total_amount,
    (select name from categories where id = expenses.expenses_type) expenses_type_name
FROM expenses
WHERE project_id = $1
GROUP BY expenses_type;