<?php

declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Settings;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Backend\Model\Session as BackendSession;
use Magento\Framework\Controller\ResultFactory;

class BrandVoiceSelection extends Action
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::generate';

    private const SESSION_KEY = 'wtai_brand_voice_selection';

    /**
     * @var BackendSession
     */
    private $backendSession;

    /**
     * @param Context $context
     * @param BackendSession $backendSession
     */
    public function __construct(
        Context $context,
        BackendSession $backendSession
    ) {
        parent::__construct($context);
        $this->backendSession = $backendSession;
    }

    /**
     * Execute action based on request
     *
     * @return \Magento\Framework\App\ResponseInterface
     */
    public function execute()
    {
        $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);

        try {
            $scope = (string) $this->getRequest()->getParam('scope', '');
            if ($scope === '') {
                $result->setData([
                    'success' => false,
                    'message' => 'Missing scope'
                ]);
                return $result;
            }

            $stored = $this->backendSession->getData(self::SESSION_KEY);
            if (!is_array($stored)) {
                $stored = [];
            }

            if ($this->getRequest()->isPost()) {
                $brandVoiceId = (string) $this->getRequest()->getParam('brand_voice_id', '');

                if ($brandVoiceId !== '') {
                    $stored[$scope] = $brandVoiceId;
                } else {
                    unset($stored[$scope]);
                }

                $this->backendSession->setData(self::SESSION_KEY, $stored);

                $result->setData([
                    'success' => true,
                    'data' => [
                        'scope' => $scope,
                        'brand_voice_id' => $stored[$scope] ?? ''
                    ]
                ]);
                return $result;
            }

            $result->setData([
                'success' => true,
                'data' => [
                    'scope' => $scope,
                    'brand_voice_id' => $stored[$scope] ?? ''
                ]
            ]);
            return $result;
        } catch (\Exception $e) {
            $message = $e->getMessage();
            if (!$message) {
                $message = (string) __('A system error has occurred. Please try again.');
            }

            $result->setData([
                'success' => false,
                'message' => $message
            ]);
            return $result;
        }
    }
}
