<?php

/**
 * JCOGS Image Pro - CpLicenseGuard
 * ================================
 * CP mutation guard for license governance policies.
 *
 * @category   ExpressionEngine Add-on
 * @package    JCOGS Image Pro
 * @author     JCOGS Design <contact@jcogs.net>
 * @copyright  Copyright (c) 2021 - 2026 JCOGS Design
 * @license    https://jcogs.net/add-ons/license/jcogs_img_pro
 * @version    2.0.6
 * @link       https://jcogs.net/
 * @since      2.0.0
 */

namespace JCOGSDesign\JCOGSImagePro\Service\License;

class CpLicenseGuard implements CpLicenseGuardInterface
{
    private CpLicensePolicyServiceInterface $policyService;
    private string $addonShortName;

    public function __construct(CpLicensePolicyServiceInterface $policyService, string $addonShortName = 'jcogs_img_pro')
    {
        $this->policyService = $policyService;
        $this->addonShortName = $addonShortName;
    }

    public function preflightRoute(string $routePath, bool $isPost): array
    {
        if (!$this->isControlPanelRequest()) {
            return [
                'raw_status' => 'na',
                'normalised_status' => 'bypass',
                'show_inline_notice' => false,
                'can_mutate' => true,
                'read_only' => false,
                'route_path' => $routePath,
            ];
        }

        $decision = $this->policyService->getPolicyDecision($this->addonShortName, $this->getSiteId(), time());
        $decision['route_path'] = $routePath;
        $decision['is_post'] = $isPost;

        return $decision;
    }

    public function assertCanMutate(string $actionLabel): void
    {
        if (!$this->isControlPanelRequest()) {
            return;
        }

        if (!$this->policyService->canMutate($this->addonShortName, $this->getSiteId(), time())) {
            throw new \RuntimeException('License policy blocks mutation action: ' . $actionLabel);
        }
    }

    private function isControlPanelRequest(): bool
    {
        if (defined('REQ') && REQ === 'CP') {
            return true;
        }

        return (bool) ee()->session->userdata('is_authorized');
    }

    private function getSiteId(): int
    {
        return (int) (ee()->config->item('site_id') ?: 1);
    }
}
