<?php

namespace Myvetshop\Module\Clinique\Security\Profiles;

use PrestaShop\PrestaShop\Adapter\LegacyContext;

abstract class AbstractProfile implements ProfileInterface
{
    protected \Access $access;

    protected LegacyContext $legacyContext;

    public function __construct(
        \Access $access,
        LegacyContext $legacyContext
    ) {
        $this->access = $access;
        $this->legacyContext = $legacyContext;
    }

    public function ensureProfileIsConfigured(): void
    {
        $context = $this->legacyContext->getContext();

        if (!$context) {
            throw new \LogicException('Context not available');
        }

        /** @var int[] $langIds */
        $langIds = \Language::getLanguages(true, false, true);
        $currendLangId = (int) $context->language->id;

        $profiles = \Profile::getProfiles($currendLangId);

        $profileId = \array_reduce(
            $profiles,
            function (?int $profileId, array $row): ?int {
                if ($row['name'] === $this->getProfileName()) {
                    return (int) $row['id_profile'];
                }

                return $profileId;
            },
            null
        );

        if (!$profileId) {
            $profile = new \Profile();
            $profile->name = [];
            foreach ($langIds as $langId) {
                $profile->name[$langId] = $this->getProfileName();
            }
            $profile->save();
        } else {
            $profile = new \Profile($profileId);
        }

        foreach ($this->getProfileModules() as $module => $access) {
            $moduleId = \Module::getModuleIdByName($module);

            if (!$moduleId) {
                continue;
            }

            $this->access->updateLgcModuleAccess((int) $profile->id, $moduleId, $access, 1);
        }

        foreach ($this->getProfileTabs() as $className => $access) {
            $tabId = \Tab::getIdFromClassName($className);

            if (!$tabId) {
                continue;
            }

            $this->access->updateLgcAccess((int) $profile->id, $tabId, $access, 1);
        }
    }
}
