<?php

namespace App\Modules\HR\Employees\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Employees\DTOs\EmployeeAssetWriteData;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Employees\Models\EmployeeAssetAssignment;
use App\Modules\HR\Employees\Repositories\EmployeeAssetAssignmentRepository;
use App\Modules\HR\Employees\Requests\StoreEmployeeAssetRequest;
use App\Modules\HR\Employees\Requests\UpdateEmployeeAssetRequest;
use App\Modules\HR\Employees\Services\EmployeeAssetAssignmentService;
use Illuminate\Http\RedirectResponse;

class EmployeeAssetAssignmentController extends Controller
{
    public function __construct(
        private readonly EmployeeAssetAssignmentService $service,
        private readonly EmployeeAssetAssignmentRepository $assignments,
    ) {}

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

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

    public function update(
        UpdateEmployeeAssetRequest $request,
        Employee $employee,
        EmployeeAssetAssignment $asset_assignment,
    ): RedirectResponse {
        $this->authorize('update', $employee);
        $row = $this->resolve($employee, $asset_assignment);
        $this->service->update($employee, $row, EmployeeAssetWriteData::fromValidated($request->validated()));

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

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

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

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