<?php

namespace App\Services\EmergencyContacts;

use App\Models\EmergencyContact;
use App\Services\PhoneFormatterService;

class EmergencyContactCrudService
{
    public function __construct(
        private PhoneFormatterService $phoneFormatter
    ) {
    }

    public function findForParent(int $contactId, int $parentId): array
    {
        $contact = EmergencyContact::query()
            ->where('id', $contactId)
            ->where('parent_id', $parentId)
            ->firstOrFail();

        return $contact->toArray();
    }

    public function update(int $contactId, int $parentId, array $payload): array
    {
        $contact = EmergencyContact::query()
            ->where('id', $contactId)
            ->where('parent_id', $parentId)
            ->firstOrFail();

        $contact->update([
            'emergency_contact_name' => $payload['name'],
            'cellphone' => $this->phoneFormatter->formatPhoneNumber($payload['cellphone']),
            'email' => $payload['email'] ?? null,
            'relation' => $payload['relation'] ?? null,
        ]);

        return $contact->toArray();
    }

    public function delete(int $contactId, int $parentId): void
    {
        $contact = EmergencyContact::query()
            ->where('id', $contactId)
            ->where('parent_id', $parentId)
            ->firstOrFail();

        $contact->delete();
    }
}
