/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/features/patients/prontuario/services/clinicalNotesSelects.js
|
| SELECTs canônicos do prontuário clínico (clinical_notes, versions, templates).
| Schema definido nas migrations 20260520000001_clinical_notes_tables.sql etc.
|--------------------------------------------------------------------------
*/

/** SELECT completo de clinical_notes (excluindo deletadas via filter no caller). */
export const CLINICAL_NOTE_SELECT = `
    id, tenant_id, owner_id, patient_id, session_event_id, note_type,
    template_id, title, content_text, content_structured,
    pinned, is_draft, created_at, updated_at, created_by, updated_by,
    deleted_at, deleted_by
`
    .replace(/\s+/g, ' ')
    .trim();

/** SELECT brief — pra listagens/cards sem content pesado. */
export const CLINICAL_NOTE_SELECT_BRIEF = `
    id, patient_id, session_event_id, note_type, template_id, title,
    pinned, is_draft, created_at, updated_at
`
    .replace(/\s+/g, ' ')
    .trim();

/** SELECT de versões — audit trail completo. */
export const CLINICAL_NOTE_VERSION_SELECT = `
    id, note_id, tenant_id, version_number, title,
    content_text, content_structured, change_reason,
    created_at, created_by
`
    .replace(/\s+/g, ' ')
    .trim();

/** SELECT de templates. */
export const CLINICAL_NOTE_TEMPLATE_SELECT = `
    id, tenant_id, owner_id, key, name, note_type, description,
    structure, is_system, is_global, active, created_at, updated_at
`
    .replace(/\s+/g, ' ')
    .trim();

/**
 * Status derivado da nota — runtime, não persistido.
 *   draft: is_draft = true
 *   active: nem draft nem deletado
 *   deleted: deleted_at set
 */
export function deriveNoteStatus(row) {
    if (!row) return 'active';
    if (row.deleted_at) return 'deleted';
    if (row.is_draft) return 'draft';
    return 'active';
}

export function flattenNoteRow(r) {
    if (!r) return r;
    return { ...r, status: deriveNoteStatus(r) };
}
