/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/features/financeiro/services/financialSelects.js
|
| SELECTs canônicos do feature financeiro. Extraído de src/composables/
| useFinancialRecords.js (que tinha BASE_SELECT inline).
|--------------------------------------------------------------------------
*/

/**
 * SELECT completo de financial_records com joins de patient + agenda_evento.
 * FKs explícitas pra evitar ambiguidade.
 */
export const FINANCIAL_RECORD_SELECT = `
    id, tenant_id, owner_id, patient_id, agenda_evento_id, billing_contract_id,
    type, amount, discount_amount, final_amount,
    status, due_date, paid_at, payment_method, payment_link,
    description, notes, created_at, updated_at,
    patients!patient_id (
        id, nome_completo, identification_color
    ),
    agenda_eventos!agenda_evento_id (
        id, inicio_em, status, tipo
    )
`
    .replace(/\s+/g, ' ')
    .trim();

/**
 * SELECT mínimo — list views simples, sem joins.
 */
export const FINANCIAL_RECORD_SELECT_BRIEF = `
    id, type, amount, final_amount, status, due_date, paid_at,
    description, payment_method, created_at, agenda_evento_id, billing_contract_id
`
    .replace(/\s+/g, ' ')
    .trim();

/**
 * Flatten — UI espera `patient_nome` flat às vezes.
 */
export function flattenFinancialRecord(r) {
    if (!r) return r;
    const patient = r.patients || null;
    const evento = r.agenda_eventos || null;
    return {
        ...r,
        patient_nome: patient?.nome_completo || r.patient_nome || '',
        patient_color: patient?.identification_color || r.patient_color || '',
        evento_inicio_em: evento?.inicio_em || r.evento_inicio_em || null,
        evento_status: evento?.status || r.evento_status || null,
        evento_tipo: evento?.tipo || r.evento_tipo || null
    };
}

/**
 * SELECT financial_exceptions — regras de cobrança em casos especiais
 * (no-show, cancelamento, etc).
 */
export const FINANCIAL_EXCEPTION_SELECT = `
    id, tenant_id, owner_id, exception_type, charge_mode, charge_value,
    charge_pct, min_hours_notice, default_consume_on_miss,
    created_at, updated_at
`
    .replace(/\s+/g, ' ')
    .trim();

/**
 * SELECT billing_contracts.
 */
export const BILLING_CONTRACT_SELECT = `
    id, tenant_id, owner_id, patient_id, charging_style,
    sessions_total, sessions_used, total_amount, status,
    start_date, end_date, deleted_at, created_at
`
    .replace(/\s+/g, ' ')
    .trim();
