<?php

namespace App\Modules\HR\Attendance\Services;

use App\Modules\HR\Attendance\Jobs\ProcessBiometricLogsJob;
use App\Modules\HR\Attendance\Models\BiometricDevice;
use App\Modules\HR\Attendance\Repositories\BiometricLogRepository;
use Illuminate\Support\Facades\DB;

class BiometricLogIngestService
{
    public function __construct(
        private readonly BiometricLogRepository $logs,
        private readonly BiometricNormalizerChain $normalizers,
    ) {}

    /**
     * @param  list<array<string, mixed>>  $rawRows
     */
    public function ingestAndQueue(BiometricDevice $device, array $rawRows, bool $queueProcess = true): int
    {
        $n = 0;
        DB::transaction(function () use ($device, $rawRows, &$n): void {
            $normalizer = $this->normalizers->forApiType((string) $device->api_type);
            foreach ($rawRows as $raw) {
                $norm = $normalizer->normalize($raw);
                if ($norm === null) {
                    continue;
                }
                $this->logs->insertRaw((int) $device->tenant_id, (int) $device->id, [
                    'employee_fingerprint_id' => $norm['employee_fingerprint_id'],
                    'punch_time' => $norm['punch_time'],
                    'raw_payload' => $norm['meta'] ?? $raw,
                ]);
                $n++;
            }
        });
        if ($queueProcess && $n > 0) {
            ProcessBiometricLogsJob::dispatch((int) $device->tenant_id, (int) $device->id);
        }

        return $n;
    }
}
