<?php
namespace App\Http\Controllers\Admin\Service;
use App\Http\Controllers\Controller;
use App\Models\Service\ServiceExecution;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ServiceExecutionController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = ServiceExecution::query()->with(['order','serviceItem','customer','technician']);
        $query->when($request->service_order_id, fn($q, $v) => $q->where('service_order_id', $v));
        $query->when($request->technician_id, fn($q, $v) => $q->where('technician_id', $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([
            'service_order_id'=>'required|exists:service_orders,id','service_item_id'=>'required|exists:service_items,id',
            'customer_id'=>'required|exists:customers,id','technician_id'=>'nullable|exists:users,id',
            'scheduled_at'=>'nullable|date','remark'=>'nullable|string',
        ]);
        $validated['status'] = 0;
        return $this->success(ServiceExecution::create($validated));
    }

    public function start(ServiceExecution $serviceExecution): JsonResponse
    {
        if ($serviceExecution->status !== 0) return $this->error('只有待执行可开始', 40001);
        $serviceExecution->update(['status'=>1,'started_at'=>now()]);
        return $this->success($serviceExecution);
    }

    public function finish(ServiceExecution $serviceExecution): JsonResponse
    {
        if ($serviceExecution->status !== 1) return $this->error('只有执行中可完成', 40001);
        $serviceExecution->update(['status'=>2,'ended_at'=>now()]);
        return $this->success($serviceExecution);
    }
}
