<?php

namespace BYDAuto\Controllers;

use BYDAuto\Actions\TestdriveCreateAction;
use BYDAuto\Models\Dealer;
use BYDAuto\Models\Vehicle;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class BYDAutoController extends Controller
{
    use ValidatesRequests;

    public function testdrive(Request $request)
    {
        $rules['name'] = ['required'];
        $rules['mobile'] = ['required'];
        $this->validate($request, $rules);
        $requestId = Str::uuid();
        $request->merge(['request_id' => $requestId]);
        (new TestdriveCreateAction())->execute($request);

        return response()->json(['code' => 0, 'message' => '提交成功', 'request_id' => $requestId]);
    }

    public function vehicle(Request $request)
    {
        $items = Vehicle::cachedItems();
        return response()->json($items);
    }

    public function province(Request $request)
    {
        $vehicle = Vehicle::query()->firstWhere('name', $request->vehicle);
        $dealers = $vehicle->dealers;
        $province = $dealers->groupBy('province')->keys();
        $data = $province->map(fn($item) => ['name' => $item]);
        return response()->json($data);
    }

    public function city(Request $request)
    {
        $vehicle = Vehicle::query()->firstWhere('name', $request->vehicle);
        if (!$vehicle) {
            throw ValidationException::withMessages(['vehicle' => '车型不存在']);
        }
        $dealers = $vehicle->dealers;
        $city = $dealers->where('province', $request->province)->groupBy('city')->keys();
        $data = $city->map(fn($item) => ['name' => $item]);
        return response()->json($data);
    }

    public function dealer(Request $request)
    {
        $vehicle = Vehicle::query()->firstWhere('name', $request->vehicle);
        if (!$vehicle) {
            throw ValidationException::withMessages(['vehicle' => '车型不存在']);
        }
        $dealer = Dealer::query()->where('province', $request->province)->where('city', $request->city)->get();
        $data = $dealer->map(fn($item) => ['name' => $item->name, 'address' => $item->address, 'erp' => $item->erp]);
        return response()->json($data);
    }
}
