<?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;

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

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

        return response()->json($this->repository->types((int) auth()->user()->tenant_id, $kind));
    }

    public function store(CompensationRequest $request, string $kind): JsonResponse
    {
        return response()->json($this->service->createType((int) $request->user()->tenant_id, $kind, $request->validated()), 201);
    }

    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
    {
        return response()->json($this->repository->updateType((int) $request->user()->tenant_id, $kind, $id, $request->validated()));
    }

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

        return response()->json([], 204);
    }
}
