<?php

namespace App\Modules\HR\Training\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Training\Models\TrainingCourse;
use App\Modules\HR\Training\Models\TrainingSession;
use App\Modules\HR\Training\Repositories\TrainingRepository;
use App\Modules\HR\Training\Requests\TrainingRequest;
use App\Modules\HR\Training\Services\TrainingService;
use Illuminate\Http\JsonResponse;

class TrainingController extends Controller
{
    public function __construct(private readonly TrainingRepository $repository, private readonly TrainingService $service) {}

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

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

    public function updateCourse(TrainingRequest $r, TrainingCourse $course): JsonResponse
    {
        return response()->json($this->repository->saveCourse((int) $course->tenant_id, $r->validated(), $course));
    }

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

    public function storeSession(TrainingRequest $r, TrainingCourse $course): JsonResponse
    {
        return response()->json($this->repository->saveSession((int) $course->tenant_id, $r->validated() + ['course_id' => $course->id]), 201);
    }

    public function updateSession(TrainingRequest $r, TrainingSession $session): JsonResponse
    {
        return response()->json($this->repository->saveSession((int) $session->tenant_id, $r->validated(), $session));
    }

    public function destroyCourse(TrainingCourse $course): JsonResponse
    {
        $this->repository->deleteCourse($course);

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

    public function destroySession(TrainingSession $session): JsonResponse
    {
        $this->repository->deleteSession($session);

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

    public function enroll(TrainingRequest $r, TrainingSession $session): JsonResponse
    {
        $this->service->enroll($session, $r->validated('employee_ids'));

        return response()->json(['enrolled' => true]);
    }
}
