<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\VoterImageImportService;
use Illuminate\Support\Facades\Log;

class VoterImageImportController extends Controller
{
    /**
     * Trigger dispatch of OCR jobs for voter page images.
     * GET/POST /api/voter-image-import?booth=2&limit=10&directory=Output
     */
    public function __invoke(Request $request, VoterImageImportService $service)
    {
        $directory = $request->input('directory', 'Output');
        $booth = $request->input('booth');
        $limit = $request->input('limit');
        $limit = $limit !== null ? (int)$limit : null;

        $result = $service->dispatchForDirectory(base_path($directory), $booth, $limit);

        if (!$result['success']) {
            return response()->json([
                'success' => false,
                'error' => $result['error'],
            ], 422);
        }

        Log::info('API triggered voter image import', $result);

        return response()->json([
            'success' => true,
            'directory' => $result['directory'],
            'jobs_dispatched' => $result['jobs_dispatched'],
            'log_ids' => $result['log_ids'],
            'booth' => $booth,
            'limit' => $limit,
        ]);
    }
}
