-- name: CreateBranch :one
INSERT INTO branches (
        name,
        location,
        wallet_id,
        branch_manager_id,
        company_id,
        is_self_owned
    )
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *;
-- name: CreateSupportedOperation :one
INSERT INTO supported_operations (name, description)
VALUES ($1, $2)
RETURNING *;
-- name: CreateBranchOperation :one
INSERT INTO branch_operations (operation_id, branch_id)
VALUES ($1, $2)
RETURNING *;
-- name: CreateBranchCashier :one
INSERT INTO branch_cashiers (user_id, branch_id)
VALUES ($1, $2)
RETURNING *;
-- name: GetAllBranches :many
SELECT *
FROM branch_details
WHERE (
        company_id = sqlc.narg('company_id')
        OR sqlc.narg('company_id') IS NULL
    )
    AND (
        is_active = sqlc.narg('is_active')
        OR sqlc.narg('is_active') IS NULL
    )
    AND (
        branch_manager_id = sqlc.narg('branch_manager_id')
        OR sqlc.narg('branch_manager_id') IS NULL
    )
    AND (
        name ILIKE '%' || sqlc.narg('query') || '%'
        OR location ILIKE '%' || sqlc.narg('query') || '%'
        OR sqlc.narg('query') IS NULL
    )
    AND (
        created_at > sqlc.narg('created_before')
        OR sqlc.narg('created_before') IS NULL
    )
    AND (
        created_at < sqlc.narg('created_after')
        OR sqlc.narg('created_after') IS NULL
    );
-- name: GetBranchByID :one
SELECT *
FROM branch_details
WHERE id = $1;
-- name: GetBranchByCompanyID :many
SELECT *
FROM branch_details
WHERE company_id = $1;
-- name: GetBranchByManagerID :many
SELECT *
FROM branch_details
WHERE branch_manager_id = $1;
-- name: SearchBranchByName :many
SELECT *
FROM branch_details
WHERE name ILIKE '%' || $1 || '%';
-- name: GetAllSupportedOperations :many
SELECT *
FROM supported_operations;
-- name: GetBranchOperations :many
SELECT branch_operations.*,
    supported_operations.name,
    supported_operations.description
FROM branch_operations
    JOIN supported_operations ON branch_operations.operation_id = supported_operations.id
WHERE branch_operations.branch_id = $1;
-- name: GetBranchByCashier :one
SELECT branches.*
FROM branch_cashiers
    JOIN branches ON branch_cashiers.branch_id = branches.id
WHERE branch_cashiers.user_id = $1;
-- name: UpdateBranch :one
UPDATE branches
SET name = COALESCE(sqlc.narg(name), name),
    location = COALESCE(sqlc.narg(location), location),
    branch_manager_id = COALESCE(sqlc.narg(branch_manager_id), branch_manager_id),
    company_id = COALESCE(sqlc.narg(company_id), company_id),
    is_self_owned = COALESCE(sqlc.narg(is_self_owned), is_self_owned),
    is_active = COALESCE(sqlc.narg(is_active), is_active),
    updated_at = CURRENT_TIMESTAMP
WHERE id = $1
RETURNING *;
-- name: DeleteBranch :exec
DELETE FROM branches
WHERE id = $1;
-- name: DeleteBranchOperation :exec
DELETE FROM branch_operations
WHERE operation_id = $1
    AND branch_id = $2;
-- name: DeleteBranchCashier :exec
DELETE FROM branch_cashiers
WHERE user_id = $1;