<?php

namespace App\Modules\HR\Employees\Services;

use App\Modules\HR\Employees\DTOs\EmergencyContactWriteData;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Employees\Models\EmployeeEmergencyContact;
use App\Modules\HR\Employees\Repositories\EmployeeEmergencyContactRepository;

class EmployeeEmergencyContactService
{
    public function __construct(
        private readonly EmployeeEmergencyContactRepository $contacts,
        private readonly EmployeeProfileActivityLogger $activity,
    ) {}

    public function store(Employee $employee, EmergencyContactWriteData $data): EmployeeEmergencyContact
    {
        $contact = $this->contacts->createPrimaryAware(array_merge($data->toArray(), [
            'tenant_id' => (int) $employee->tenant_id,
            'employee_id' => (int) $employee->id,
            'created_by' => auth()->id(),
        ]));

        $this->activity->log($employee, 'emergency_contact_created', __('activity_logs.actions.employee_emergency_contact_created', [
            'name' => $employee->full_name,
            'contact' => $contact->full_name,
        ]));

        return $contact;
    }

    public function update(
        Employee $employee,
        EmployeeEmergencyContact $contact,
        EmergencyContactWriteData $data,
    ): EmployeeEmergencyContact {
        $updated = $this->contacts->updatePrimaryAware($contact, $data->toArray());
        $this->activity->log($employee, 'emergency_contact_updated', __('activity_logs.actions.employee_emergency_contact_updated', [
            'name' => $employee->full_name,
            'contact' => $updated->full_name,
        ]));

        return $updated;
    }

    public function destroy(Employee $employee, EmployeeEmergencyContact $contact): void
    {
        $label = $contact->full_name;
        $this->contacts->delete($contact);
        $this->activity->log($employee, 'emergency_contact_deleted', __('activity_logs.actions.employee_emergency_contact_deleted', [
            'name' => $employee->full_name,
            'contact' => $label,
        ]));
    }
}
