-- 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, 
    COALESCE(
        (
            SELECT SUM(t_hist.amount)
            FROM transactions t_hist
            WHERE categories.id = t_hist.category_id 
            AND t_hist.date < @from_date
        )
    , 0)::decimal(12,2) as balance, 
    COALESCE(
        (
            SELECT SUM(t_this.amount)
            FROM transactions t_this
            WHERE categories.id = t_this.category_id 
            AND t_this.date BETWEEN @from_date AND @to_date
        )
    , 0)::decimal(12,2) as activity
FROM categories
INNER JOIN category_groups ON categories.category_group_id = category_groups.id
WHERE category_groups.budget_id = @budget_id
GROUP BY categories.id, categories.name, category_groups.name;