<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Grid;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use WriteTextAI\WriteTextAI\ViewModel\AiModels as AiModelsViewModel;

class GetAiModels extends Action
{
    /**
     * @var AiModelsViewModel
     */
    protected $aiModels;

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

    /**
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);

        try {
            $aiModels = $this->aiModels->getAiModels();
            $hasAiModels = $this->aiModels->hasAiModels();

            $result->setData([
                'success' => true,
                'data' => [
                    'hasAiModels' => (bool)$hasAiModels,
                    'aiModels' => is_array($aiModels) ? $aiModels : []
                ]
            ]);
        } catch (\Exception $e) {
            $result->setData([
                'success' => false,
                'data' => [
                    'hasAiModels' => false,
                    'aiModels' => []
                ]
            ]);
        }

        return $result;
    }
}
