-- name: CreateTransaction :one
INSERT INTO financial_transactions (
  fot_id, data_cobranca, tipo_evento, tipo_servico, professional_name, 
  whatsapp, cpf, tabela_free, valor_free, valor_extra, descricao_extra, 
  total_pagar, data_pagamento, pgto_ok
) VALUES (
  $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14
) RETURNING *;

-- name: ListTransactionsByFot :many
SELECT * FROM financial_transactions 
WHERE fot_id = $1 
ORDER BY data_cobranca DESC;

-- name: ListTransactions :many
SELECT t.*, f.fot as fot_numero
FROM financial_transactions t
LEFT JOIN cadastro_fot f ON t.fot_id = f.id
ORDER BY t.data_cobranca DESC;

-- name: SumTotalByFot :one
SELECT COALESCE(SUM(total_pagar), 0)::NUMERIC 
FROM financial_transactions 
WHERE fot_id = $1;

-- name: UpdateTransaction :one
UPDATE financial_transactions SET 
  fot_id = $2, data_cobranca = $3, tipo_evento = $4, tipo_servico = $5, 
  professional_name = $6, whatsapp = $7, cpf = $8, tabela_free = $9, 
  valor_free = $10, valor_extra = $11, descricao_extra = $12, 
  total_pagar = $13, data_pagamento = $14, pgto_ok = $15,
  atualizado_em = NOW()
WHERE id = $1
RETURNING *;

-- name: DeleteTransaction :exec
DELETE FROM financial_transactions WHERE id = $1;

-- name: GetTransaction :one
SELECT * FROM financial_transactions WHERE id = $1;


-- name: ListTransactionsByProfessional :many
SELECT t.*, f.fot as fot_numero, e.nome as empresa_nome, c.nome as curso_nome
FROM financial_transactions t
LEFT JOIN cadastro_fot f ON t.fot_id = f.id
LEFT JOIN empresas e ON f.empresa_id = e.id
LEFT JOIN cursos c ON f.curso_id = c.id
WHERE 
  t.profissional_id = $1 
  OR (
     $2::text <> '' AND 
     REGEXP_REPLACE(t.cpf, '\D', '', 'g') = REGEXP_REPLACE($2, '\D', '', 'g')
  )
ORDER BY t.data_cobranca DESC;
