<?php

namespace App\Modules\HR\Employees\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Employees\DTOs\EmployeeSkillWriteData;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Employees\Models\EmployeeSkill;
use App\Modules\HR\Employees\Repositories\EmployeeSkillRepository;
use App\Modules\HR\Employees\Requests\StoreEmployeeSkillRequest;
use App\Modules\HR\Employees\Requests\UpdateEmployeeSkillRequest;
use App\Modules\HR\Employees\Services\EmployeeSkillService;
use Illuminate\Http\RedirectResponse;

class EmployeeSkillController extends Controller
{
    public function __construct(
        private readonly EmployeeSkillService $service,
        private readonly EmployeeSkillRepository $skills,
    ) {}

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

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

    public function update(
        UpdateEmployeeSkillRequest $request,
        Employee $employee,
        EmployeeSkill $skill,
    ): RedirectResponse {
        $this->authorize('update', $employee);
        $row = $this->resolve($employee, $skill);
        $this->service->update($employee, $row, EmployeeSkillWriteData::fromValidated($request->validated()));

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

    public function destroy(Employee $employee, EmployeeSkill $skill): RedirectResponse
    {
        $this->authorize('update', $employee);
        $row = $this->resolve($employee, $skill);
        $this->service->destroy($employee, $row);

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

    private function resolve(Employee $employee, EmployeeSkill $skill): EmployeeSkill
    {
        $row = $this->skills->findForEmployee((int) $employee->tenant_id, (int) $employee->id, (int) $skill->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' => 'skills'])
            ->with('status', $status);
    }
}
