<?php

namespace App\Http\Controllers;

use App\Http\Requests\NewCarBulkUpdateIdsRequest;
use App\Http\Requests\NewCarBulkUpdateRequest;
use App\Services\NewCarBulkUpdateService;
use Illuminate\Http\JsonResponse;

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

    public function getNewCarData(NewCarBulkUpdateIdsRequest $request, NewCarBulkUpdateService $service): JsonResponse
    {
        return response()->json([
            'new_cars' => $service->getNewCarData($request->input('new_car_ids')),
        ]);
    }

    public function update(NewCarBulkUpdateRequest $request, NewCarBulkUpdateService $service): JsonResponse
    {
        $mode = $request->input('mode');
        $newCarIds = $request->input('new_car_ids');

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

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

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

    public function deleteFinanceExamples(
        NewCarBulkUpdateIdsRequest $request,
        NewCarBulkUpdateService $service
    ): JsonResponse {
        $deletedCount = $service->deleteFinanceExamples($request->input('new_car_ids'));

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