-- name: CreateCategory :one
INSERT INTO categories (
    name,
    icon,
    description,
    letter,
    parent_id,
    parent_path,
    status,
    sort
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING *;

-- name: UpdateCategory :one
UPDATE categories
SET
    name = COALESCE(sqlc.narg(name), name),
    icon = COALESCE(sqlc.narg(icon), icon),
    description = COALESCE(sqlc.narg(description), description),
    letter = COALESCE(sqlc.narg(letter), letter),
    parent_id = COALESCE(sqlc.narg(parent_id), parent_id),
    parent_path = COALESCE(sqlc.narg(parent_path), parent_path),
    sort = COALESCE(sqlc.narg(sort), sort),
    status = COALESCE(sqlc.narg(status), status),
    updated_at = NOW()
WHERE id = $1
RETURNING *;

-- name: GetCategory :one
SELECT * 
FROM categories 
WHERE id = $1
LIMIT 1;

-- name: ListCategories :many
SELECT * FROM categories 
WHERE status = 0;

-- name: ListCategoriesByPath :many
SELECT * FROM categories 
WHERE parent_path LIKE $1
AND status = 0
ORDER BY sort DESC, id ASC;

-- name: CountCategoriesCondition :one
SELECT COUNT(*) FROM categories
WHERE (NOT @is_status::Boolean OR status = @status)
    AND (NOT @is_id::Boolean OR id = @id)
    AND (NOT @is_parent_id::Boolean OR parent_id = @parent_id)
    AND (@name::text = '' OR name ILIKE '%' || @name || '%');

-- name: ListCategoriesCondition :many
SELECT * FROM categories
WHERE (NOT @is_status::Boolean OR status = @status)
    AND (NOT @is_id::Boolean OR id = @id)
    AND (NOT @is_parent_id::Boolean OR parent_id = @parent_id)
    AND (@name::text = '' OR name ILIKE '%' || @name || '%')
ORDER BY sort DESC, id ASC
OFFSET @skip
LIMIT @size;

-- name: AllCategories :many
SELECT * FROM categories 
WHERE status = 0
ORDER BY sort DESC, id ASC;

-- name: ExistsCategories :one
SELECT EXISTS (
    SELECT 1 FROM categories
);

-- name: ListCategoriesRecursive :many
WITH RECURSIVE dist AS (SELECT categories.*
                        FROM categories
                        WHERE status = 0
                        UNION ALL
                        SELECT categories.*
                        FROM categories,
                             dist
                        WHERE categories.id = dist.parent_id)
SELECT DISTINCT *
FROM dist
ORDER BY sort DESC, id ASC;