-- name: CreateUsuario :one
INSERT INTO usuarios (email, senha_hash, role, ativo)
VALUES ($1, $2, $3, false)
RETURNING *;

-- name: GetUsuarioByEmail :one
SELECT u.id, u.email, u.senha_hash, u.role, u.ativo, u.criado_em, u.atualizado_em,
       COALESCE(cp.nome, cc.nome, '') as nome,
       COALESCE(cp.whatsapp, cc.telefone, '') as whatsapp,
       e.id as empresa_id,
       e.nome as empresa_nome
FROM usuarios u
LEFT JOIN cadastro_profissionais cp ON u.id = cp.usuario_id
LEFT JOIN cadastro_clientes cc ON u.id = cc.usuario_id
LEFT JOIN empresas e ON cc.empresa_id = e.id
WHERE u.email = $1 LIMIT 1;

-- name: GetUsuarioByID :one
SELECT u.id, u.email, u.senha_hash, u.role, u.ativo, u.criado_em, u.atualizado_em,
       COALESCE(cp.nome, cc.nome, '') as nome,
       COALESCE(cp.whatsapp, cc.telefone, '') as whatsapp,
       e.id as empresa_id,
       e.nome as empresa_nome
FROM usuarios u
LEFT JOIN cadastro_profissionais cp ON u.id = cp.usuario_id
LEFT JOIN cadastro_clientes cc ON u.id = cc.usuario_id
LEFT JOIN empresas e ON cc.empresa_id = e.id
WHERE u.id = $1 LIMIT 1;

-- name: DeleteUsuario :exec
DELETE FROM usuarios
WHERE id = $1;

-- name: ListUsuariosPending :many
SELECT u.id, u.email, u.role, u.ativo, u.criado_em,
       COALESCE(cp.nome, cc.nome, '') as nome,
       COALESCE(cp.whatsapp, cc.telefone, '') as whatsapp,
       e.id as empresa_id,
       e.nome as empresa_nome
FROM usuarios u
LEFT JOIN cadastro_profissionais cp ON u.id = cp.usuario_id
LEFT JOIN cadastro_clientes cc ON u.id = cc.usuario_id
LEFT JOIN empresas e ON cc.empresa_id = e.id
WHERE u.ativo = false
ORDER BY u.criado_em DESC;

-- name: UpdateUsuarioAtivo :one
UPDATE usuarios
SET ativo = $2, atualizado_em = NOW()
WHERE id = $1
RETURNING *;
-- name: UpdateUsuarioRole :one
UPDATE usuarios
SET role = $2, atualizado_em = NOW()
WHERE id = $1
RETURNING *;

-- name: ListAllUsuarios :many
SELECT id, email, role, ativo, criado_em, atualizado_em
FROM usuarios
ORDER BY criado_em DESC;

-- name: CreateCadastroCliente :one
INSERT INTO cadastro_clientes (usuario_id, empresa_id, nome, telefone)
VALUES ($1, $2, $3, $4)
RETURNING *;
