<?php

namespace App\Modules\HR\Employees\Controllers;

use App\Http\Controllers\Controller;
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;
use App\Modules\HR\Employees\Requests\StoreEmergencyContactRequest;
use App\Modules\HR\Employees\Requests\UpdateEmergencyContactRequest;
use App\Modules\HR\Employees\Services\EmployeeEmergencyContactService;
use Illuminate\Http\RedirectResponse;

class EmployeeEmergencyContactController extends Controller
{
    public function __construct(
        private readonly EmployeeEmergencyContactService $service,
        private readonly EmployeeEmergencyContactRepository $contacts,
    ) {}

    public function store(StoreEmergencyContactRequest $request, Employee $employee): RedirectResponse
    {
        $this->authorize('update', $employee);
        $this->service->store($employee, EmergencyContactWriteData::fromValidated($request->validated()));

        return $this->backToTab($employee, __('employees.flash.emergency_contact_created'));
    }

    public function update(
        UpdateEmergencyContactRequest $request,
        Employee $employee,
        EmployeeEmergencyContact $emergency_contact,
    ): RedirectResponse {
        $this->authorize('update', $employee);
        $contact = $this->resolve($employee, $emergency_contact);
        $this->service->update($employee, $contact, EmergencyContactWriteData::fromValidated($request->validated()));

        return $this->backToTab($employee, __('employees.flash.emergency_contact_updated'));
    }

    public function destroy(Employee $employee, EmployeeEmergencyContact $emergency_contact): RedirectResponse
    {
        $this->authorize('update', $employee);
        $contact = $this->resolve($employee, $emergency_contact);
        $this->service->destroy($employee, $contact);

        return $this->backToTab($employee, __('employees.flash.emergency_contact_deleted'));
    }

    private function resolve(Employee $employee, EmployeeEmergencyContact $contact): EmployeeEmergencyContact
    {
        $row = $this->contacts->findForEmployee((int) $employee->tenant_id, (int) $employee->id, (int) $contact->id);
        abort_if($row === null, 404);

        return $row;
    }

    private function backToTab(Employee $employee, string $status): RedirectResponse
    {
        return redirect()
            ->route('hr.employees.show', ['employee' => $employee, 'tab' => 'emergency_contacts'])
            ->with('status', $status);
    }
}
