<?php

namespace App\Services\Intune;

use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;

class WindowsDriverUpdateProfileNormalizer implements PolicyTypeNormalizer
{
    public function __construct(
        private readonly DefaultPolicyNormalizer $defaultNormalizer,
    ) {}

    public function supports(string $policyType): bool
    {
        return $policyType === 'windowsDriverUpdateProfile';
    }

    /**
     * @return array{status: string, settings: array<int, array<string, mixed>>, settings_table?: array<string, mixed>, warnings: array<int, string>}
     */
    public function normalize(?array $snapshot, string $policyType, ?string $platform = null): array
    {
        $snapshot = $snapshot ?? [];
        $normalized = $this->defaultNormalizer->normalize($snapshot, $policyType, $platform);

        if ($snapshot === []) {
            return $normalized;
        }

        $block = $this->buildDriverUpdateBlock($snapshot);

        if ($block !== null) {
            $normalized['settings'][] = $block;
            $normalized['settings'] = array_values(array_filter($normalized['settings']));
        }

        return $normalized;
    }

    /**
     * @return array<string, mixed>
     */
    public function flattenForDiff(?array $snapshot, string $policyType, ?string $platform = null): array
    {
        $snapshot = $snapshot ?? [];
        $normalized = $this->normalize($snapshot, $policyType, $platform);

        return $this->defaultNormalizer->flattenNormalizedForDiff($normalized);
    }

    private function buildDriverUpdateBlock(array $snapshot): ?array
    {
        $entries = [];

        $displayName = Arr::get($snapshot, 'displayName');

        if (is_string($displayName) && $displayName !== '') {
            $entries[] = ['key' => 'Name', 'value' => $displayName];
        }

        $approvalType = Arr::get($snapshot, 'approvalType');

        if (is_string($approvalType) && $approvalType !== '') {
            $entries[] = ['key' => 'Approval type', 'value' => $approvalType];
        }

        $deferral = Arr::get($snapshot, 'deploymentDeferralInDays');

        if (is_int($deferral) || (is_numeric($deferral) && (string) (int) $deferral === (string) $deferral)) {
            $entries[] = ['key' => 'Deployment deferral (days)', 'value' => (int) $deferral];
        }

        $deviceReporting = Arr::get($snapshot, 'deviceReporting');

        if (is_int($deviceReporting) || (is_numeric($deviceReporting) && (string) (int) $deviceReporting === (string) $deviceReporting)) {
            $entries[] = ['key' => 'Devices reporting', 'value' => (int) $deviceReporting];
        }

        $newUpdates = Arr::get($snapshot, 'newUpdates');

        if (is_int($newUpdates) || (is_numeric($newUpdates) && (string) (int) $newUpdates === (string) $newUpdates)) {
            $entries[] = ['key' => 'New driver updates', 'value' => (int) $newUpdates];
        }

        $inventorySyncStatus = Arr::get($snapshot, 'inventorySyncStatus');

        if (is_array($inventorySyncStatus)) {
            $state = Arr::get($inventorySyncStatus, 'driverInventorySyncState');

            if (is_string($state) && $state !== '') {
                $entries[] = ['key' => 'Inventory sync state', 'value' => $state];
            }

            $lastSuccessful = $this->formatDateTime(Arr::get($inventorySyncStatus, 'lastSuccessfulSyncDateTime'));

            if ($lastSuccessful !== null) {
                $entries[] = ['key' => 'Last successful inventory sync', 'value' => $lastSuccessful];
            }
        }

        if ($entries === []) {
            return null;
        }

        return [
            'type' => 'keyValue',
            'title' => 'Driver Update Profile',
            'entries' => $entries,
        ];
    }

    private function formatDateTime(mixed $value): ?string
    {
        if (! is_string($value) || $value === '') {
            return null;
        }

        try {
            return CarbonImmutable::parse($value)->toDateTimeString();
        } catch (\Throwable) {
            return $value;
        }
    }
}
