-- name: CreateApi :one
INSERT INTO sys_apis (name, group_name, method, path, sort)
VALUES ($1, $2, $3, $4, $5)
RETURNING id;

-- name: ListAllApis :many
SELECT *
FROM sys_apis
ORDER BY sort ASC;

-- name: ListApis :many
SELECT *
FROM sys_apis
WHERE (sqlc.arg('name')::text = '' OR name ILIKE '%' || sqlc.arg('name') || '%')
  AND (sqlc.arg('group_name')::text = '' OR group_name ILIKE '%' || sqlc.arg('group_name') || '%')
  AND (sqlc.arg('method')::text = '' OR method = sqlc.arg('method'))
ORDER BY id
LIMIT $1 OFFSET $2;

-- name: CountApis :one
SELECT COUNT(*)
FROM sys_apis
WHERE (sqlc.arg('name')::text = '' OR name ILIKE '%' || sqlc.arg('name') || '%')
  AND (sqlc.arg('group_name')::text = '' OR group_name ILIKE '%' || sqlc.arg('group_name') || '%')
  AND (sqlc.arg('method')::text = '' OR method = sqlc.arg('method'));

-- name: GetApiByID :one
SELECT *
FROM sys_apis
WHERE id = $1;

-- name: UpdateApi :execrows
UPDATE sys_apis
SET name       = $2,
    method     = $3,
    path       = $4,
    sort       = $5,
    group_name = $6
WHERE id = $1;

-- name: DeleteApi :execrows
DELETE
FROM sys_apis
WHERE id = $1;

-- name: CreateApiPermission :exec
INSERT INTO sys_api_permission (api_id, permission_id)
VALUES ($1, $2);

-- name: DeleteApiPermission :exec
DELETE
FROM sys_api_permission
WHERE api_id = $1;

-- name: ListApiGroups :many
SELECT DISTINCT group_name
FROM sys_apis;

