<?php

namespace App\Modules\HR\Attendance\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Attendance\Models\AttendanceRecord;
use App\Modules\HR\Attendance\Repositories\BiometricDeviceRepository;
use App\Modules\HR\Attendance\Requests\IngestBiometricLogsRequest;
use App\Modules\HR\Attendance\Services\BiometricLogIngestService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class BiometricLogIngestController extends Controller
{
    public function __invoke(
        Request $request,
        int $device,
        IngestBiometricLogsRequest $httpRequest,
        BiometricDeviceRepository $devices,
        BiometricLogIngestService $ingest,
    ): JsonResponse {
        $this->authorize('import', AttendanceRecord::class);
        $tenant = $request->user()?->tenant;
        abort_if($tenant === null, 403);
        $d = $devices->findForTenant((int) $tenant->id, $device);
        abort_if($d === null, 404);
        $n = $ingest->ingestAndQueue($d, $httpRequest->validated('punches'), true);

        return response()->json(['ingested' => $n]);
    }
}
