<?php

namespace App\Http\Controllers\Admin\Care;

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

class CareExceptionController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = CareException::query()->with(['profile.customer', 'reporter', 'handler']);
        $query->when($request->care_profile_id, fn($q, $v) => $q->where('care_profile_id', $v));
        $query->when($request->level, fn($q, $v) => $q->where('level', $v));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));

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

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'care_profile_id' => 'required|exists:care_profiles,id',
            'level' => 'required|integer|in:1,2,3',
            'description' => 'required|string',
            'images' => 'nullable|array',
        ]);
        $validated['reporter_id'] = auth()->id();
        $validated['status'] = 0;

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

    public function show(CareException $careException): JsonResponse
    {
        return $this->success($careException->load(['profile.customer', 'reporter', 'handler']));
    }

    public function update(Request $request, CareException $careException): JsonResponse
    {
        $validated = $request->validate([
            'level' => 'sometimes|integer|in:1,2,3',
            'description' => 'sometimes|string',
            'images' => 'nullable|array',
        ]);
        $careException->update($validated);
        return $this->success($careException);
    }

    public function handle(Request $request, CareException $careException): JsonResponse
    {
        if ($careException->status === 2) {
            return $this->error('该异常已处理', 40001);
        }
        $validated = $request->validate([
            'handle_result' => 'required|string',
        ]);
        $careException->update([
            'handle_result' => $validated['handle_result'],
            'handler_id' => auth()->id(),
            'handle_at' => now(),
            'status' => 2,
        ]);
        return $this->success($careException);
    }
}
