<?php
declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Model;

use WriteTextAI\WriteTextAI\Api\StoresLanguagesInterface;
use WriteTextAI\WriteTextAI\Api\Data\StoresLanguagesResultInterfaceFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Store\Api\Data\StoreInterface;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;

/**
 * Class StoresLanguages
 * API implementation for retrieving store IDs and languages
 */
class StoresLanguages implements StoresLanguagesInterface
{
    /**
     * @var StoresLanguagesResultInterfaceFactory
     */
    private $storesLanguagesResultFactory;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var ResolverInterface
     */
    private $localeResolver;

    /**
     * @var StoreHelper
     */
    private $storeHelper;

    /**
     * @param StoresLanguagesResultInterfaceFactory $storesLanguagesResultFactory
     * @param StoreManagerInterface $storeManager
     * @param ResolverInterface $localeResolver
     * @param StoreHelper $storeHelper
     */
    public function __construct(
        StoresLanguagesResultInterfaceFactory $storesLanguagesResultFactory,
        StoreManagerInterface $storeManager,
        ResolverInterface $localeResolver,
        StoreHelper $storeHelper
    ) {
        $this->storesLanguagesResultFactory = $storesLanguagesResultFactory;
        $this->storeManager = $storeManager;
        $this->localeResolver = $localeResolver;
        $this->storeHelper = $storeHelper;
    }

    /**
     * Get store IDs and their corresponding languages
     *
     * @return \WriteTextAI\WriteTextAI\Api\Data\StoresLanguagesResultInterface
     */
    public function getStoresLanguages()
    {
        $storeIds = [];
        $languages = [];
        $result = [];
        /** @var StoreInterface[] $stores */
        $stores = $this->storeManager->getStores(true); // Include admin store

        foreach ($stores as $store) {
            $storeIds[] = (string) $store->getId();
            
            // Get locale code for the store
            $currentStoreId = $this->storeManager->getStore()->getId();
            $this->storeManager->setCurrentStore($store->getId());
            
            $formattedLanguage = $this->storeHelper->getFormattedLanguage($store->getId());
            $languages[] = $formattedLanguage;
            
            // Restore original store
            $this->storeManager->setCurrentStore($currentStoreId);
        }

        $result = $this->storesLanguagesResultFactory->create();
        $result->setStoreIds($storeIds);
        $result->setLanguages($languages);

        return $result;
    }
}
