<?php

namespace App\Services;

use App\Models\Customer;

class OltCustomerMatcher
{
    public function enrich(array $snapshot): array
    {
        $devices = (array) ($snapshot['devices'] ?? []);
        if ($devices === []) {
            $snapshot['customer_match_summary'] = ['total_devices' => 0, 'matched' => 0, 'unmatched' => 0];
            return $snapshot;
        }

        $customers = Customer::query()->select('id', 'customer_code', 'name', 'contact_phone', 'ip_address', 'onumac', 'fibercode')->get();
        $byIp = $customers->filter(fn ($c) => filled($c->ip_address))->keyBy(fn ($c) => $this->ip($c->ip_address));
        $byMac = $customers->filter(fn ($c) => filled($c->onumac))->keyBy(fn ($c) => $this->mac($c->onumac));
        $bySerial = $customers->filter(fn ($c) => filled($c->fibercode))->keyBy(fn ($c) => $this->serial($c->fibercode));
        $matched = 0;

        $snapshot['devices'] = collect($devices)->map(function (array $device) use ($byIp, $byMac, $bySerial, &$matched) {
            $customer = null;
            if (filled($device['mac'] ?? null)) $customer = $byMac->get($this->mac($device['mac']));
            if (! $customer && filled($device['serial'] ?? null)) $customer = $bySerial->get($this->serial($device['serial']));
            if (! $customer && filled($device['ip'] ?? null)) $customer = $byIp->get($this->ip($device['ip']));
            if ($customer) {
                $matched++;
                $device['customer'] = ['id' => $customer->id, 'code' => $customer->customer_code, 'name' => $customer->name, 'phone' => $customer->contact_phone, 'pppoe' => $customer->ip_address];
                $device['match_status'] = 'matched';
            } else {
                $device['customer'] = null;
                $device['match_status'] = 'unmatched';
            }
            return $device;
        })->all();
        $snapshot['customer_match_summary'] = ['total_devices' => count($devices), 'matched' => $matched, 'unmatched' => count($devices) - $matched];
        return $snapshot;
    }

    private function mac(string $value): string { return strtoupper(preg_replace('/[^0-9A-F]/i', '', $value)); }
    private function serial(string $value): string { return strtoupper(trim($value)); }
    private function ip(string $value): string { return strtolower(trim($value)); }
}
