<?php

namespace App\Http\Controllers;

use App\Http\Requests\DealershipBulkUpdateRequest;
use App\Services\DealershipBulkUpdateService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DealershipBulkUpdateController extends Controller
{
    public function __construct()
    {
        $this->middleware([
            'permission:edit-dealerships',
        ]);
    }

    public function getFields(DealershipBulkUpdateService $service): JsonResponse
    {
        return response()->json([
            'fields' => $service->getFields(),
        ]);
    }

    public function getDealershipData(Request $request, DealershipBulkUpdateService $service): JsonResponse
    {
        $request->validate([
            'dealership_ids' => 'required|array|max:100',
            'dealership_ids.*' => 'exists:dealerships,id',
        ]);

        return response()->json([
            'dealerships' => $service->getDealershipData($request->input('dealership_ids')),
        ]);
    }

    public function update(DealershipBulkUpdateRequest $request, DealershipBulkUpdateService $service): JsonResponse
    {
        $mode = $request->input('mode');
        $dealershipIds = $request->input('dealership_ids');

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

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

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