<?php

namespace App\Master\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Jobs\ImportCapVehiclesJob;
use App\Master\Http\Resources\CapVehicleList;
use App\Master\Http\Resources\CapVehicleView;
use App\Master\Models\CapVehicle;
use Mtc\MercuryDataModels\VehicleType;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class CapVehicleController extends Controller
{
    public function index(Request $request)
    {
        $query = CapVehicle::query();

        if ($request->filled('manufacturer')) {
            $query->byManufacturer($request->input('manufacturer'));
        }

        if ($request->filled('model')) {
            $query->byModel($request->input('model'));
        }

        if ($request->filled('derivative')) {
            $query->byDerivative($request->input('derivative'));
        }

        if ($request->filled('type')) {
            $query->ofType($request->input('type'));
        }

        if ($request->filled('cap_id')) {
            $query->where('cap_id', $request->input('cap_id'));
        }

        if ($request->filled('cap_code')) {
            $query->where('cap_code', 'like', '%' . $request->input('cap_code') . '%');
        }

        $vehicles = $query
            ->orderBy('manufacturer')
            ->orderBy('short_model')
            ->orderBy('derivative')
            ->paginate($request->input('per_page', 25));

        return new CapVehicleList($vehicles);
    }

    public function show(CapVehicle $capVehicle)
    {
        $capVehicle->load(['make', 'vehicleModel']);

        return new CapVehicleView($capVehicle);
    }

    public function stats(): JsonResponse
    {
        return response()->json([
            'total' => CapVehicle::count(),
            'cars' => CapVehicle::cars()->count(),
            'lcvs' => CapVehicle::lcvs()->count(),
        ]);
    }

    public function upload(Request $request): JsonResponse
    {
        $request->validate([
            'file' => ['required', 'file', 'mimes:csv,txt'],
            'type' => ['required', Rule::in([VehicleType::CAR->value, VehicleType::LCV->value])],
            'clear_existing' => ['sometimes', 'boolean'],
        ]);

        $file = $request->file('file');
        $type = $request->input('type');
        $clearExisting = $request->boolean('clear_existing', false);

        $path = $file->store('cap-imports', 'local');

        ImportCapVehiclesJob::dispatch($path, $type, $clearExisting, 'local');

        return response()->json([
            'message' => 'Import job queued successfully',
            'type' => $type,
            'clear_existing' => $clearExisting,
        ]);
    }
}
