<?php

namespace App\Http\Controllers;

use App\Http\Requests\VehicleBulkUpdateRequest;
use App\Services\VehicleBulkUpdateService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class VehicleBulkUpdateController extends Controller
{
    public function getFields(VehicleBulkUpdateService $service): JsonResponse
    {
        return response()->json([
            'fields' => $service->getFields(),
        ]);
    }

    public function getVehicleData(Request $request, VehicleBulkUpdateService $service): JsonResponse
    {
        $request->validate([
            'vehicle_ids' => 'required|array|max:100',
            'vehicle_ids.*' => 'exists:vehicles,id',
        ]);

        return response()->json([
            'vehicles' => $service->getVehicleData($request->input('vehicle_ids')),
        ]);
    }

    public function update(VehicleBulkUpdateRequest $request, VehicleBulkUpdateService $service): JsonResponse
    {
        $mode = $request->input('mode');
        $vehicleIds = $request->input('vehicle_ids');

        $data = $mode === 'same'
            ? ['field' => $request->input('field'), 'value' => $request->input('value')]
            : ['updates' => $request->input('updates', [])];

        $updatedCount = $service->update($mode, $vehicleIds, $data);

        return response()->json([
            'success' => true,
            'updated_count' => $updatedCount,
            'message' => "{$updatedCount} vehicle(s) updated successfully.",
        ]);
    }

    public function deleteFinanceExamples(Request $request, VehicleBulkUpdateService $service): JsonResponse
    {
        $request->validate([
            'vehicle_ids' => 'required|array|max:100',
            'vehicle_ids.*' => 'exists:vehicles,id',
        ]);

        $deletedCount = $service->deleteFinanceExamples($request->input('vehicle_ids'));

        return response()->json([
            'success' => true,
            'deleted_count' => $deletedCount,
            'message' => "Finance examples deleted from {$deletedCount} vehicle(s).",
        ]);
    }

    public function requestFinanceQuotes(Request $request, VehicleBulkUpdateService $service): JsonResponse
    {
        $request->validate([
            'vehicle_ids' => 'required|array|max:100',
            'vehicle_ids.*' => 'exists:vehicles,id',
        ]);

        $result = $service->requestFinanceQuotes($request->input('vehicle_ids'));

        return response()->json([
            'success' => true,
            'requested_count' => $result['requested'],
            'failed_count' => $result['failed'],
            'message' => "Finance quotes requested for {$result['requested']} vehicle(s)." .
                ($result['failed'] > 0 ? " {$result['failed']} failed." : ''),
        ]);
    }
}
