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

-- name: GetAccount :one
SELECT accounts.* FROM accounts
WHERE accounts.id = $1;

-- name: GetAccounts :many
SELECT accounts.* FROM accounts
WHERE accounts.budget_id = $1
AND accounts.is_open = TRUE
ORDER BY accounts.name;

-- name: GetAccountsWithBalance :many
SELECT accounts.id, accounts.name, accounts.on_budget, accounts.is_open, accounts.last_reconciled,
        (SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW())::decimal(12,2) as working_balance,
        (SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status IN ('Cleared', 'Reconciled'))::decimal(12,2) as cleared_balance,
        (SELECT SUM(transactions.amount) FROM transactions WHERE transactions.account_id = accounts.id AND transactions.date < NOW() AND transactions.status = 'Reconciled')::decimal(12,2) as reconciled_balance
FROM accounts
WHERE accounts.budget_id = $1
AND accounts.is_open = TRUE
ORDER BY accounts.name;

-- name: SearchAccounts :many
SELECT accounts.id, accounts.budget_id, accounts.name, 'account' as type FROM accounts
WHERE accounts.budget_id = @budget_id
AND accounts.is_open = TRUE
AND accounts.name LIKE @search
ORDER BY accounts.name;

-- name: UpdateAccount :one
UPDATE accounts
SET name = $1,
    on_budget = $2,
    is_open = $3
WHERE accounts.id = $4
RETURNING *;

-- name: SetLastReconciled :exec
UPDATE accounts
SET last_reconciled = NOW()
WHERE accounts.id = $1;