<?php

namespace App\Modules\HR\Compensation\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Compensation\Repositories\CompensationRepository;
use App\Modules\HR\Compensation\Requests\CompensationRequest;
use App\Modules\HR\Compensation\Services\CompensationService;
use App\Modules\HR\Employees\Models\Employee;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class CompensationController extends Controller
{
    public function __construct(private readonly CompensationRepository $repository, private readonly CompensationService $service) {}

    public function index(string $kind): JsonResponse|View
    {
        abort_unless(in_array($kind, ['allowance', 'deduction'], true), 404);

        $types = $this->repository->types((int) auth()->user()->tenant_id, $kind);

        return request()->expectsJson()
            ? response()->json($types)
            : view('pages.hr.'.($kind === 'allowance' ? 'allowances' : 'deductions').'.index', compact('types', 'kind'));
    }

    public function store(CompensationRequest $request, string $kind): JsonResponse|RedirectResponse
    {
        $type = $this->service->createType((int) $request->user()->tenant_id, $kind, $request->validated());

        return $request->expectsJson() ? response()->json($type, 201) : back()->with('success', __('compensation.flash.created'));
    }

    public function attach(CompensationRequest $request, string $kind, Employee $employee): JsonResponse
    {
        abort_unless((int) $employee->tenant_id === (int) $request->user()->tenant_id, 404);

        return response()->json($this->service->attach((int) $employee->tenant_id, (int) $employee->id, $kind, $request->validated()), 201);
    }

    public function update(CompensationRequest $request, string $kind, int $id): JsonResponse|RedirectResponse
    {
        $type = $this->repository->updateType((int) $request->user()->tenant_id, $kind, $id, $request->validated());

        return $request->expectsJson() ? response()->json($type) : back()->with('success', __('compensation.flash.updated'));
    }

    public function destroy(string $kind, int $id): JsonResponse|RedirectResponse
    {
        $this->repository->deleteType((int) auth()->user()->tenant_id, $kind, $id);

        return request()->expectsJson() ? response()->json([], 204) : back()->with('success', __('compensation.flash.deleted'));
    }
}
