<?php

namespace Functional\Tracking\Http\Controllers;

use Functional\Tracking\Http\Requests\StoreBodyMetricRequest;
use Functional\Tracking\Http\Resources\BodyMetricResource;
use Functional\Tracking\Models\BodyMetric;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Symfony\Component\HttpFoundation\Response;

/**
 * Mensurations (poids, masse grasse) de l'utilisateur authentifié.
 */
class BodyMetricsController
{
    private const DEFAULT_PER_PAGE = 20;

    /** GET /api/metrics */
    public function index(Request $request): AnonymousResourceCollection
    {
        $metrics = BodyMetric::query()
            ->where('user_id', auth()->id())
            ->orderByDesc('measured_on')
            ->paginate((int) $request->query('per_page', self::DEFAULT_PER_PAGE));

        return BodyMetricResource::collection($metrics);
    }

    /**
     * POST /api/metrics — idempotent par (user_id, measured_on) : une mensuration existante
     * pour cette date est mise à jour plutôt que dupliquée (contrainte unique en base).
     */
    public function store(StoreBodyMetricRequest $request): JsonResponse
    {
        $data = $request->validated();

        $metric = BodyMetric::query()->updateOrCreate(
            ['user_id' => auth()->id(), 'measured_on' => $data['measured_on']],
            ['weight' => $data['weight'] ?? null, 'body_fat' => $data['body_fat'] ?? null, 'notes' => $data['notes'] ?? null],
        );

        return (new BodyMetricResource($metric))
            ->response()
            ->setStatusCode(Response::HTTP_CREATED);
    }
}
