<?php

namespace Modules\HR\Services\CrossChex;

use Carbon\Carbon;
use Modules\Employee\Models\Employee;
use Modules\HR\Models\AttendanceLog;
use Modules\HR\Models\BiometricDevice;

class AttendanceLogProcessor
{
    public function process(array $data): bool
    {
        $workNo = $data['employee']['workno'] ?? null;
        $checkTime = $data['checktime'] ?? null;

        if (! $workNo || ! $checkTime) {
            return false;
        }

        $employee = Employee::find($workNo);

        if (! $employee) {
            return false;
        }

        $device = BiometricDevice::firstOrCreate(
            [
                'device_uid' => $data['device']['serial_number'] ?? null,
            ],
            [
                'name'      => $data['device']['name'] ?? '',
                'status'    => true,
                'branch_id' => null,
            ]
        );

        $currentLogTime = Carbon::parse($checkTime)
            ->timezone('Asia/Dhaka');

        if ($this->isDuplicate($employee->id, $currentLogTime)) {
            return false;
        }

        AttendanceLog::create([
            'employee_id'    => $employee->id,
            'device_id'      => $device->id,
            'log_time'       => $currentLogTime,
            'type'           => null,
            'source'         => 'biometric',
            'device_user_id' => $workNo,
            'raw_punch'      => $data['uuid'] ?? null,
            'punch_state'    => null,
            'is_processed'   => false,
            'raw_payload'    => json_encode($data),
        ]);

        return true;
    }

    private function isDuplicate(
        int $employeeId,
        Carbon $currentLogTime
    ): bool {
        $lastLog = AttendanceLog::query()
            ->where('employee_id', $employeeId)
            ->latest('log_time')
            ->first();

        if (! $lastLog) {
            return false;
        }

        return $currentLogTime->diffInSeconds(
            Carbon::parse($lastLog->log_time)
        ) <= 60;
    }
}
