<?php

namespace App\Http\Controllers;

use App\Http\Requests\WorkoutSessionsRequest;
use App\Http\Resources\WorkoutSessionsResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class WorkoutSessionController extends Controller
{
    public function index(WorkoutSessionsRequest $request): AnonymousResourceCollection
    {
        $workoutSessions = $request->user()
            ->workouts()
            ->latest('started_at')
            ->paginate($request->integer('per_page', 15))
            ->withQueryString();

        return WorkoutSessionsResource::collection($workoutSessions);
    }

    public function store(WorkoutSessionsRequest $request): JsonResponse
    {
        $workoutSession = $request->user()
            ->workouts()
            ->create($request->validated());

        return (new WorkoutSessionsResource($workoutSession))
            ->response()
            ->setStatusCode(201);
    }
}
