-- name: CreateIncome :one
INSERT INTO incomes (project_id, budget_id, amount, income_at, income_type, income_bank, remark, status, created_user_id) 
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING *;

-- name: UpdateIncome :one
UPDATE incomes
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),
    income_at = COALESCE(sqlc.narg(income_at), income_at),
    income_type = COALESCE(sqlc.narg(income_type), income_type),
    income_bank = COALESCE(sqlc.narg(income_bank), income_bank),
    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: GetIncome :one
SELECT * 
FROM incomes 
WHERE id = $1
LIMIT 1;

-- name: SumIncome :one
SELECT SUM(amount)::numeric
FROM incomes;

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

-- name: StatisticsIncome :many
SELECT SUM(amount)::numeric as total_amount,
    (select name from categories where id = incomes.income_type) income_type_name
FROM incomes
GROUP BY income_type;

-- name: StatisticsIncomeByProjectID :many
SELECT SUM(amount)::numeric as total_amount,
    (select name from categories where id = incomes.income_type) income_type_name
FROM incomes
WHERE project_id = $1
GROUP BY income_type;