<?php

namespace App\Http\Controllers;

use App\Http\Requests\BulkCreateNewCarRequest;
use App\NewCarRepository;
use Illuminate\Http\JsonResponse;
use Mtc\MercuryDataModels\Franchise;

class NewCarBulkCreateController extends Controller
{
    /**
     * Bulk create new cars for every selected model of a franchise's make.
     */
    public function store(BulkCreateNewCarRequest $request, NewCarRepository $repository): JsonResponse
    {
        $franchise = Franchise::query()->findOrFail($request->input('franchise_id'));

        $cars = $repository->bulkCreateForFranchise(
            $franchise,
            $request->input('model_ids', []),
            [
                'template_id' => $request->input('template_id'),
                'form_id' => $request->input('form_id'),
                'test_drive_form_id' => $request->input('test_drive_form_id'),
                'vehicle_type' => $request->input('vehicle_type'),
            ],
        );

        return response()->json([
            'data' => $cars->map(fn ($car) => [
                'id' => $car->id,
                'name' => $car->name,
                'make_id' => $car->make_id,
                'model_id' => $car->model_id,
            ])->values(),
            'created_count' => $cars->count(),
        ], JsonResponse::HTTP_CREATED);
    }
}
