<?php

namespace Easymailing\App\Core\Provider\Woocommerce\Batch;

use Easymailing\App\Api\Client;
use Easymailing\App\Core\Log\LogManager;
use Easymailing\App\Core\Provider\Woocommerce\Model\LogType;
use Easymailing\App\Repository\ConfigRepository;
use Easymailing\App\Utils\Api;

class StoresBatchOperations
{

	private $configRepository;
	private $apiClient;
	private $logManager;

	public function __construct(ConfigRepository $configRepository, Client $apiClient, LogManager $logManager)
	{
		$this->configRepository = $configRepository;
		$this->apiClient = $apiClient;
		$this->logManager = $logManager;
	}

    public function getStoresBatchOperations(): array
    {
		$this->logManager->createLog(LogType::BATCH, "start StoresBatchOperations");

        $client = $this->apiClient;
	    $config = $this->configRepository->getSynchronizationConfig();
        $batchOperations = [];

        try {
            $shopId = $config->getShopId();
            $audience = $config->getAudience();
            $group = $config->getGroup();
            $locale = $config->getLanguage();
            $timeZone = $config->getTimezone();

            $stores = $client->getStores();

            $storeIds = [];
            foreach ($stores as $store) {
                $storeIds[] = Api::extractUuid($store->id);
            }

	        $urlBase = "/stores";
	        $method = in_array($shopId, $storeIds) ? "PUT" : "POST";
	        $url = $method === "PUT" ? "{$urlBase}/{$shopId}" : $urlBase;

	        $body = [
		        'name' => get_bloginfo('name'),
		        'domain' => home_url(),
		        'audience' => $audience,
		        'group' => $group,
		        'locale' => $locale,
		        'timezone' => $timeZone
	        ];

	        if ($method === "POST") {
		        $body['resource_id'] = $shopId;
	        }

	        $line = [
		        "method" => $method,
		        "path" => $url,
		        "body" => json_encode($body),
		        'external_identifier' => null
	        ];

	        $batchOperations[] = $line;

	        $this->logManager->createLog(LogType::BATCH, "End StoresBatchOperations");

            return $batchOperations;
        } catch (\Exception $e) {
            $this->logManager->createLog(LogType::BATCH, sprintf("Error in StoresBatchOperations: %s", $e->getMessage()));
        }

        return $batchOperations;
    }
}
