<?php

namespace BookneticApp\Providers\FSCode\Services;

use BookneticApp\Providers\Core\Bootstrap;
use BookneticApp\Providers\FSCode\Clients\FSCodeAPIClient;
use BookneticApp\Providers\Helpers\Helper;

class FSCodeApiService
{
    private FSCodeApiClient $client;

    public function __construct(FSCodeApiClient $client)
    {
        $this->client = $client;
    }

    public function checkUpdatesAndSync(array $addons): array
    {
        $response = $this->client->post('addons/check_update', [
            'domain' => site_url(),
            'addons' => $addons,
        ]);

        $responseBody = $response['body'] ?? [];

        if (isset($responseBody['unowned_addons']) && is_array($responseBody['unowned_addons'])) {
            $this->handleUnownedAddonUsage($responseBody['unowned_addons']);
        }

        return $responseBody;
    }

    private function handleUnownedAddonUsage(array $addons): void
    {
        $normalizedAddons = [];

        foreach ($addons as $addon) {
            if (! is_array($addon) || empty($addon['slug'])) {
                continue;
            }

            $normalizedAddons[ $addon['slug'] ] = $addon;
        }

        Helper::setOption('synced_addons', $normalizedAddons, false);
    }

    public function sync(array $addons = []): void
    {
        foreach (Bootstrap::getAddons() as $addon) {
            $addons[$addon::getAddonSlug()] = $addon::getVersion();
        }

        $this->checkUpdatesAndSync($addons);
    }
}
