<?php

namespace App\Modules\HR\Performance\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Performance\Models\PerformanceCycle;
use App\Modules\HR\Performance\Models\PerformanceReview;
use App\Modules\HR\Performance\Repositories\PerformanceRepository;
use App\Modules\HR\Performance\Requests\PerformanceRequest;
use App\Modules\HR\Performance\Services\PerformanceService;
use Illuminate\Http\JsonResponse;

class PerformanceController extends Controller
{
    public function __construct(private readonly PerformanceRepository $repository, private readonly PerformanceService $service) {}

    public function cycles(): JsonResponse
    {
        return response()->json($this->repository->cycles((int) auth()->user()->tenant_id));
    }

    public function storeCycle(PerformanceRequest $r): JsonResponse
    {
        return response()->json($this->repository->saveCycle((int) $r->user()->tenant_id, $r->validated()), 201);
    }

    public function updateCycle(PerformanceRequest $r, PerformanceCycle $cycle): JsonResponse
    {
        return response()->json($this->repository->saveCycle((int) $cycle->tenant_id, $r->validated(), $cycle));
    }

    public function reviews(): JsonResponse
    {
        $employee = request()->routeIs('me.*') ? (int) auth()->user()->employee_id : null;

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

    public function storeReview(PerformanceRequest $r): JsonResponse
    {
        return response()->json($this->repository->saveReview((int) $r->user()->tenant_id, $r->validated()), 201);
    }

    public function selfUpdate(PerformanceRequest $r, PerformanceReview $review): JsonResponse
    {
        abort_unless((int) $review->employee_id === (int) $r->user()->employee_id, 403);

        return response()->json($this->service->selfUpdate($review, $r->validated()));
    }

    public function managerUpdate(PerformanceRequest $r, PerformanceReview $review): JsonResponse
    {
        return response()->json($this->service->managerUpdate($review, $r->validated(), (int) $r->user()->id));
    }

    public function destroyCycle(PerformanceCycle $cycle): JsonResponse
    {
        $this->repository->deleteCycle($cycle);

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

    public function destroyReview(PerformanceReview $review): JsonResponse
    {
        $this->repository->deleteReview($review);

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