<?php

namespace App\Http\Controllers\Admin\Room;

use App\Http\Controllers\Controller;
use App\Models\Room\CallRecord;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CallRecordController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = CallRecord::query()->with(['room', 'customer', 'handler']);
        $query->when($request->room_id, fn($q, $v) => $q->where('room_id', $v));
        $query->when($request->type, fn($q, $v) => $q->where('type', $v));
        $query->when($request->status, fn($q, $v) => $q->where('status', $v));

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

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'room_id' => 'required|exists:rooms,id',
            'customer_id' => 'nullable|exists:customers,id',
            'type' => 'nullable|integer|in:1,2,3,4',
            'remark' => 'nullable|string|max:255',
        ]);
        $validated['status'] = 0;

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

    public function handle(Request $request, CallRecord $callRecord): JsonResponse
    {
        if ($callRecord->status === 2) {
            return $this->error('该呼叫已完成', 40001);
        }
        $callRecord->update([
            'status' => 2,
            'handler_id' => auth()->id(),
            'handle_at' => now(),
            'remark' => $request->input('remark', $callRecord->remark),
        ]);
        return $this->success($callRecord);
    }
}
