<?php

namespace App\Http\Controllers\Admin\Care;

use App\Http\Controllers\Controller;
use App\Models\Care\HealthMetric;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class HealthMetricController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = HealthMetric::query()->with('recorder');
        $query->when($request->care_profile_id, fn($q, $v) => $q->where('care_profile_id', $v));
        $query->when($request->metric_type, fn($q, $v) => $q->where('metric_type', $v));
        $query->when($request->start_date, fn($q, $v) => $q->where('recorded_at', '>=', $v));
        $query->when($request->end_date, fn($q, $v) => $q->where('recorded_at', '<=', $v));

        return $this->paginate($query->latest('recorded_at')->paginate($request->input('per_page', 50)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'care_profile_id' => 'required|exists:care_profiles,id',
            'metric_type' => 'required|string|max:30',
            'value' => 'required|numeric',
            'unit' => 'nullable|string|max:10',
            'recorded_at' => 'sometimes|date',
            'remark' => 'nullable|string|max:255',
        ]);
        $validated['recorder_id'] = auth()->id();
        $validated['recorded_at'] = $validated['recorded_at'] ?? now();

        return $this->success(HealthMetric::create($validated));
    }
}
