-- name: CreateProject :one
INSERT INTO projects (id, name, start_at, end_at, customer_id, total_money, description, apply_at, apply_user_id, manager_id, members, status, created_user_id)
VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
RETURNING *;

-- name: UpdateProject :one
UPDATE projects
SET
    name = COALESCE(sqlc.narg(name), name),
    start_at = COALESCE(sqlc.narg(start_at), start_at),
    end_at = COALESCE(sqlc.narg(end_at), end_at),
    customer_id = COALESCE(sqlc.narg(customer_id), customer_id),
    total_money = COALESCE(sqlc.narg(total_money), total_money),
    description = COALESCE(sqlc.narg(description), description),
    apply_at = COALESCE(sqlc.narg(apply_at), apply_at),
    apply_user_id = COALESCE(sqlc.narg(apply_user_id), apply_user_id),
    manager_id = COALESCE(sqlc.narg(manager_id), manager_id),
    members = COALESCE(sqlc.narg(members), members),
    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: GetProject :one
SELECT * 
FROM projects 
WHERE id = $1
LIMIT 1;

-- name: AllProjects :many
SELECT * FROM projects
WHERE status > -1
ORDER BY id DESC;

-- name: CountProjects :one
SELECT COUNT(1)
FROM projects
WHERE status = $1;

-- name: ListProjects :many
SELECT * 
FROM projects
WHERE status = $1
ORDER BY id DESC
LIMIT $1 OFFSET $2;

-- name: StatisticsProjects :many
select name,
       (select sum(amount)::numeric from incomes where project_id = projects.id) income,
       (select sum(amount)::numeric from expenses where project_id = projects.id) expense
from projects;

-- name: StatisticsProjectItem :one
select name,
       (select sum(amount)::numeric from incomes where project_id = projects.id) income,
       (select sum(amount)::numeric from expenses where project_id = projects.id) expense
from projects
where projects.id = $1;