<?php

namespace App\Modules\HR\Employees\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Employees\DTOs\EmploymentHistoryWriteData;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Employees\Models\EmployeeEmploymentHistory;
use App\Modules\HR\Employees\Repositories\EmployeeEmploymentHistoryRepository;
use App\Modules\HR\Employees\Requests\StoreEmploymentHistoryRequest;
use App\Modules\HR\Employees\Requests\UpdateEmploymentHistoryRequest;
use App\Modules\HR\Employees\Services\EmployeeEmploymentHistoryService;
use Illuminate\Http\RedirectResponse;

class EmployeeEmploymentHistoryController extends Controller
{
    public function __construct(
        private readonly EmployeeEmploymentHistoryService $service,
        private readonly EmployeeEmploymentHistoryRepository $histories,
    ) {}

    public function store(StoreEmploymentHistoryRequest $request, Employee $employee): RedirectResponse
    {
        $this->service->store($employee, EmploymentHistoryWriteData::fromValidated($request->validated()));

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

    public function update(UpdateEmploymentHistoryRequest $request, Employee $employee, EmployeeEmploymentHistory $employment_history): RedirectResponse
    {
        $row = $this->resolve($employee, $employment_history);
        $this->service->update($employee, $row, EmploymentHistoryWriteData::fromValidated($request->validated()));

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

    public function destroy(Employee $employee, EmployeeEmploymentHistory $employment_history): RedirectResponse
    {
        $this->authorize('update', $employee);
        $this->service->destroy($employee, $this->resolve($employee, $employment_history));

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

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

        return $row;
    }

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