-- name: CreateSysUser :one
INSERT INTO sys_user (
    uuid, 
    email, 
    username, 
    hashed_password, 
    salt, 
    avatar, 
    gender, 
    department_id, 
    role_id, 
    status, 
    change_password_at, 
    created_at, 
    updated_at
) VALUES (
    $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13
) RETURNING *;

-- name: UpdateSysUser :one
UPDATE sys_user
SET username           = $2,
    hashed_password    = $3,
    avatar             = $4,
    gender             = $5,
    department_id      = $6,
    role_id            = $7,
    status             = $8,
    change_password_at = $9,
    updated_at         = $10
WHERE id = $1
RETURNING *;

-- name: GetSysUser :one
SELECT * FROM sys_user
WHERE id = $1 LIMIT 1;

-- name: GetSysUserByEmail :one
SELECT * FROM sys_user
WHERE email = $1 LIMIT 1;

-- name: CountSysUser :one
SELECT COUNT(*) FROM sys_user
WHERE status = 0;

-- name: ListSysUser :many
SELECT * FROM sys_user
WHERE status = 0
ORDER BY created_at DESC;

-- name: CountSysUserCondition :one
SELECT COUNT(*) FROM sys_user
WHERE (NOT @is_status::Boolean OR status = @status)
    AND (NOT @is_id::Boolean OR id = @id)
    AND (@username::text = '' OR username ILIKE '%' || @username || '%')
    AND (@email::text = '' OR email ILIKE '%' || @email || '%');

-- name: ListSysUserCondition :many
SELECT id, uuid, email, username, avatar, gender, department_id, role_id, status, change_password_at, created_at, updated_at,
       (SELECT name FROM sys_department WHERE ID = sys_user.department_id)          AS department_name,
       (SELECT display_name
        FROM sys_role
        WHERE id = sys_user.role_id)                                                AS role_name
FROM sys_user
WHERE (NOT @is_status::Boolean OR sys_user.status = @status)
    AND (NOT @is_id::Boolean OR sys_user.id = @id)
    AND (@username::text = '' OR sys_user.username ILIKE '%' || @username || '%')
    AND (@email::text = '' OR sys_user.email ILIKE '%' || @email || '%')
ORDER BY created_at DESC
OFFSET @skip
LIMIT @size;

-- name: ExistsSysUser :one
SELECT EXISTS (
    SELECT 1 FROM sys_user
);

-- name: ListSysUserByIds :many
SELECT * FROM sys_user
WHERE id = ANY($1::int[]);