<?php

namespace App\Modules\HR\Offboarding\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Offboarding\DTOs\OffboardingData;
use App\Modules\HR\Offboarding\Models\OffboardingCase;
use App\Modules\HR\Offboarding\Repositories\OffboardingRepository;
use App\Modules\HR\Offboarding\Requests\ChecklistItemRequest;
use App\Modules\HR\Offboarding\Requests\OffboardingRequest;
use App\Modules\HR\Offboarding\Services\OffboardingService;
use Illuminate\Http\JsonResponse;

class OffboardingController extends Controller
{
    public function __construct(private readonly OffboardingRepository $repository, private readonly OffboardingService $service) {}

    public function index(): JsonResponse
    {
        $this->authorize('viewAny', OffboardingCase::class);

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

    public function store(OffboardingRequest $r): JsonResponse
    {
        return response()->json($this->service->create(OffboardingData::fromValidated($r->validated()), (int) $r->user()->tenant_id, (int) $r->user()->id), 201);
    }

    public function show(OffboardingCase $case): JsonResponse
    {
        $this->authorize('view', $case);

        return response()->json($case->load(['employee', 'checklistItems']));
    }

    public function update(OffboardingRequest $r, OffboardingCase $case): JsonResponse
    {
        $this->authorize('update', $case);
        abort_unless($case->status === 'draft', 422);

        return response()->json($this->repository->update($case, $r->validated()));
    }

    public function action(OffboardingCase $case, string $action): JsonResponse
    {
        $this->authorize('manage', $case);

        return response()->json($this->service->transition($case, $action));
    }

    public function addChecklistItem(ChecklistItemRequest $r, OffboardingCase $case): JsonResponse
    {
        $this->authorize('manage', $case);

        return response()->json($this->service->addChecklistItem($case, $r->validated(), (int) $r->user()->id), 201);
    }
}
