<?php

namespace Functional\Routines\Http\Controllers;

use Functional\Routines\Http\Requests\StoreRoutineRequest;
use Functional\Routines\Http\Requests\UpdateRoutineRequest;
use Functional\Routines\Http\Resources\RoutineResource;
use Functional\Routines\Models\Routine;
use Functional\Routines\Services\RoutineService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response as HttpResponse;
use Symfony\Component\HttpFoundation\Response;

/**
 * CRUD des routines de l'utilisateur authentifié, strictement scopées par auth()->id().
 */
class RoutinesController
{
    public function __construct(
        private readonly RoutineService $routineService,
    ) {
    }

    /** GET /api/routines */
    public function index(): AnonymousResourceCollection
    {
        $routines = Routine::query()
            ->where('user_id', auth()->id())
            ->with('routineExercises.exercise')
            ->orderBy('name')
            ->paginate();

        return RoutineResource::collection($routines);
    }

    /** POST /api/routines */
    public function store(StoreRoutineRequest $request): JsonResponse
    {
        $routine = $this->routineService->create($request->user(), $request->validated());

        return (new RoutineResource($routine))
            ->response()
            ->setStatusCode(Response::HTTP_CREATED);
    }

    /** GET /api/routines/{routine} */
    public function show(int $routine): RoutineResource
    {
        return new RoutineResource($this->findForUser($routine));
    }

    /** PUT /api/routines/{routine} */
    public function update(UpdateRoutineRequest $request, int $routine): RoutineResource
    {
        $updated = $this->routineService->update($this->findForUser($routine), $request->validated());

        return new RoutineResource($updated);
    }

    /** DELETE /api/routines/{routine} */
    public function destroy(int $routine): HttpResponse
    {
        $this->findForUser($routine)->delete();

        return response()->noContent();
    }

    /** Charge la routine (avec ses exercices) en la scopant strictement à l'utilisateur courant. */
    private function findForUser(int $routineId): Routine
    {
        return Routine::query()
            ->where('user_id', auth()->id())
            ->with('routineExercises.exercise')
            ->findOrFail($routineId);
    }
}
