<?php

namespace App\Http\Controllers\Api\V1;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\VehicleDispatch\VehicleDispatchUpdateRequest;
use App\Services\VehicleDispatchService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class VehicleDispatchController extends Controller
{
    public function __construct(
        private readonly VehicleDispatchService $service
    ) {}

    /**
     * 배차차량 목록 조회
     */
    public function index(Request $request): JsonResponse
    {
        $params = $request->only([
            'search',
            'status',
            'start_date',
            'end_date',
            'per_page',
            'page',
        ]);

        $dispatches = $this->service->index($params);

        return ApiResponse::success($dispatches, __('message.fetched'));
    }

    /**
     * 배차차량 통계 조회
     */
    public function stats(): JsonResponse
    {
        $stats = $this->service->stats();

        return ApiResponse::success($stats, __('message.fetched'));
    }

    /**
     * 배차차량 상세 조회
     */
    public function show(int $id): JsonResponse
    {
        try {
            $dispatch = $this->service->show($id);

            return ApiResponse::success($dispatch, __('message.fetched'));
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return ApiResponse::error(__('error.not_found'), 404);
        }
    }

    /**
     * 배차차량 수정
     */
    public function update(VehicleDispatchUpdateRequest $request, int $id): JsonResponse
    {
        try {
            $dispatch = $this->service->update($id, $request->validated());

            return ApiResponse::success($dispatch, __('message.updated'));
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return ApiResponse::error(__('error.not_found'), 404);
        }
    }
}
