-- name: CreateCategoryGroup :one
INSERT INTO category_groups
(name, budget_id)
VALUES ($1, $2)
RETURNING *;

-- name: GetCategoryGroups :many
SELECT category_groups.* FROM category_groups 
WHERE category_groups.budget_id = $1;

-- name: CreateCategory :one
INSERT INTO categories
(name, category_group_id)
VALUES ($1, $2)
RETURNING *;

-- name: GetCategories :many
SELECT categories.*, category_groups.name as group FROM categories
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
WHERE category_groups.budget_id = $1;

-- name: GetCategoriesWithBalance :many
SELECT categories.id, categories.name, category_groups.name as group, SUM(t_hist.amount)::decimal(12,2) as balance, SUM(t_this.amount)::decimal(12,2) as activity
FROM categories
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
INNER JOIN transactions t_hist ON categories.id = t_hist.category_id AND t_hist.date < @from_date
INNER JOIN transactions t_this ON categories.id = t_this.category_id AND t_this.date >= @from_date AND t_this.date < @to_date
WHERE category_groups.budget_id = @budget_id
GROUP BY categories.id, categories.name, category_groups.name;