<?php

namespace App\Http\Controllers\Admin\Care;

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

class CareProfileController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = CareProfile::query()->with('customer');
        $query->when($request->customer_id, fn($q, $v) => $q->where('customer_id', $v));
        $query->when($request->type, fn($q, $v) => $q->where('type', $v));
        $query->when($request->risk_level, fn($q, $v) => $q->where('risk_level', $v));

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

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'reservation_id' => 'nullable|exists:reservations,id',
            'type' => 'required|integer|in:1,2',
            'baby_name' => 'nullable|string|max:50',
            'baby_gender' => 'nullable|integer|in:1,2',
            'baby_birthday' => 'nullable|date',
            'birth_weight' => 'nullable|numeric|min:0',
            'birth_method' => 'nullable|integer|in:1,2',
            'allergies' => 'nullable|string',
            'medical_history' => 'nullable|string',
            'risk_level' => 'sometimes|integer|in:0,1,2',
            'assessment' => 'nullable|array',
        ]);
        return $this->success(CareProfile::create($validated));
    }

    public function show(CareProfile $careProfile): JsonResponse
    {
        return $this->success($careProfile->load(['customer', 'plans.nurse', 'records', 'exceptions', 'healthMetrics']));
    }

    public function update(Request $request, CareProfile $careProfile): JsonResponse
    {
        $validated = $request->validate([
            'baby_name' => 'nullable|string|max:50',
            'baby_gender' => 'nullable|integer|in:1,2',
            'baby_birthday' => 'nullable|date',
            'birth_weight' => 'nullable|numeric|min:0',
            'birth_method' => 'nullable|integer|in:1,2',
            'allergies' => 'nullable|string',
            'medical_history' => 'nullable|string',
            'risk_level' => 'sometimes|integer|in:0,1,2',
            'assessment' => 'nullable|array',
        ]);
        $careProfile->update($validated);
        return $this->success($careProfile);
    }

    public function destroy(CareProfile $careProfile): JsonResponse
    {
        $careProfile->delete();
        return $this->success(null);
    }
}
