<?php

namespace App\Services\Intune;

use Illuminate\Support\Arr;

class VersionDiff
{
    public function compare(array $from, array $to): array
    {
        $fromFlat = Arr::dot($from);
        $toFlat = Arr::dot($to);

        $added = [];
        $removed = [];
        $changed = [];

        foreach ($toFlat as $key => $value) {
            if (! array_key_exists($key, $fromFlat)) {
                $added[$key] = $value;

                continue;
            }

            if ($fromFlat[$key] !== $value) {
                $changed[$key] = [
                    'from' => $fromFlat[$key],
                    'to' => $value,
                ];
            }
        }

        foreach ($fromFlat as $key => $value) {
            if (! array_key_exists($key, $toFlat)) {
                $removed[$key] = $value;
            }
        }

        $summary = [
            'added' => count($added),
            'removed' => count($removed),
            'changed' => count($changed),
            'message' => sprintf(
                '%d added, %d removed, %d changed',
                count($added),
                count($removed),
                count($changed)
            ),
        ];

        return [
            'summary' => $summary,
            'added' => $added,
            'removed' => $removed,
            'changed' => $changed,
        ];
    }
}
