<?php

namespace App\Services\Care\Dentistry;

use App\Models\DentalVisitNote;
use App\Models\Organization;
use App\Models\Visit;
use App\Services\Care\AuditLogger;

class DentalVisitNoteService
{
    /**
     * @param  array{chief_complaint?: ?string, soft_tissue?: ?string, occlusion?: ?string, notes?: ?string}  $data
     */
    public function upsert(
        Organization $organization,
        Visit $visit,
        array $data,
        string $ownerRef,
        ?string $actorRef = null,
    ): DentalVisitNote {
        $visit->loadMissing('patient');

        $note = DentalVisitNote::owned($ownerRef)
            ->where('visit_id', $visit->id)
            ->first();

        $attributes = [
            'owner_ref' => $ownerRef,
            'organization_id' => $organization->id,
            'visit_id' => $visit->id,
            'patient_id' => $visit->patient_id,
            'chief_complaint' => $data['chief_complaint'] ?? null,
            'soft_tissue' => $data['soft_tissue'] ?? null,
            'occlusion' => $data['occlusion'] ?? null,
            'notes' => $data['notes'] ?? null,
            'recorded_by' => $actorRef ?? $ownerRef,
            'recorded_at' => now(),
        ];

        if ($note) {
            $note->update($attributes);
        } else {
            $note = DentalVisitNote::create($attributes);
        }

        AuditLogger::record($ownerRef, 'dental.notes.saved', $organization->id, $actorRef, DentalVisitNote::class, $note->id);

        return $note->fresh();
    }
}
