<?php

namespace App\Http\Controllers;

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

class WorkoutSessionController extends Controller
{
    public function index(WorkoutSessionsRequest $request): AnonymousResourceCollection
    {
        $validated = $request->validated();
        $workoutSessionsQuery = $request->user()->workouts();

        if (isset($validated['date'])) {
            $referenceDate = CarbonImmutable::createFromFormat('!Y-m-d', $validated['date']);

            $workoutSessionsQuery->whereBetween('started_at', [
                $referenceDate->startOfDay(),
                $referenceDate->endOfDay(),
            ]);
        }

        $workoutSessions = $workoutSessionsQuery
            ->latest('started_at')
            ->paginate($request->integer('per_page', 15))
            ->withQueryString();

        return WorkoutSessionsResource::collection($workoutSessions);
    }

    public function calendar(WorkoutSessionsCalendarRequest $request): JsonResponse
    {
        $month = $request->validated('month') ?? now()->format('Y-m');
        $referenceDate = CarbonImmutable::createFromFormat('!Y-m', $month);
        $startDate = $referenceDate->startOfMonth();
        $endDate = $referenceDate->endOfMonth();

        $days = $request->user()
            ->workouts()
            ->whereBetween('started_at', [$startDate->startOfDay(), $endDate->endOfDay()])
            ->selectRaw('DATE(started_at) as date, COUNT(*) as workouts_count')
            ->groupByRaw('DATE(started_at)')
            ->orderBy('date')
            ->get()
            ->map(fn ($workoutSession): array => [
                'date' => CarbonImmutable::parse((string) $workoutSession->date)->toDateString(),
                'workoutsCount' => (int) $workoutSession->workouts_count,
            ])
            ->values();

        return response()->json([
            'data' => [
                'month' => $referenceDate->format('Y-m'),
                'startDate' => $startDate->toDateString(),
                'endDate' => $endDate->toDateString(),
                'days' => $days,
            ],
        ]);
    }

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

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