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

declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Cron;

use WriteTextAI\WriteTextAI\Cron\BaseCron;
use Magento\User\Model\UserFactory;
use WriteTextAI\WriteTextAI\Model\Api\Session as ApiSession;
use Magento\Framework\App\Config\ScopeConfigInterface;
use WriteTextAI\WriteTextAI\Model\BulkTransferCronManager;
use WriteTextAI\WriteTextAI\Logger\CronLogger;
use Magento\Cron\Model\Schedule;

/**
 * Grid Transfer Cron Job
 */
class GridTransfer extends BaseCron
{
    /**
     * @var BulkTransferCronManager
     */
    protected $bulkTransferCronManager;

    /**
     * @var CronLogger
     */
    protected $cronLogger;

    /**
     * Constructor
     *
     * @param UserFactory $userFactory
     * @param ApiSession $apiSession
     * @param ScopeConfigInterface $scopeConfig
     * @param BulkTransferCronManager $bulkTransferCronManager
     * @param CronLogger $cronLogger
     */
    public function __construct(
        UserFactory $userFactory,
        ApiSession $apiSession,
        ScopeConfigInterface $scopeConfig,
        BulkTransferCronManager $bulkTransferCronManager,
        CronLogger $cronLogger
    ) {
        parent::__construct($userFactory, $apiSession, $scopeConfig);
        $this->bulkTransferCronManager = $bulkTransferCronManager;
        $this->cronLogger = $cronLogger;
    }

    /**
     * Execute grid transfer process
     *
     * @param Schedule $schedule
     * @return void
     */
    public function execute(?Schedule $schedule = null): void
    {
        $this->cronLogger->logRequest('GridTransfer cron job started');
        
        try {
            // Get the bulk_request_id from the schedule message
            $bulkRequestId = null;
            if ($schedule && $schedule->getMessages()) {
                $message = $schedule->getMessages();
                $this->cronLogger->logRequest('Schedule message: ' . $message);
                
                // Parse the bulk_request_id from the message
                // Expected format: "bulk_request_id:123" or just "123"
                if (preg_match('/bulk_request_id:(\d+)/', $message, $matches)) {
                    $bulkRequestId = (int)$matches[1];
                } elseif (is_numeric($message)) {
                    $bulkRequestId = (int)$message;
                } else {
                    // Try to extract any number from the message
                    if (preg_match('/(\d+)/', $message, $matches)) {
                        $bulkRequestId = (int)$matches[1];
                    }
                }
            }
            
            if (!$bulkRequestId) {
                $this->cronLogger->logRequest('No bulk_request_id found in schedule message');
                if ($schedule) {
                    $schedule->setStatus(Schedule::STATUS_ERROR);
                    $schedule->setMessages('Error: No bulk_request_id found in schedule message');
                }
                return;
            }
            
            $this->cronLogger->logRequest('Processing bulk transfer request ID: ' . $bulkRequestId);
            
            // Process the bulk transfer using BulkTransferCronManager
            $success = $this->bulkTransferCronManager->processBulkTransfer($bulkRequestId);
            
            if ($success) {
                $this->cronLogger->logRequest('Bulk transfer completed successfully for request ID: ' . $bulkRequestId);
                if ($schedule) {
                    $schedule->setStatus(Schedule::STATUS_SUCCESS);
                    $schedule->setMessages('Bulk transfer completed successfully');
                }
            } else {
                $this->cronLogger->logRequest('Bulk transfer failed for request ID: ' . $bulkRequestId);
                if ($schedule) {
                    $schedule->setStatus(Schedule::STATUS_ERROR);
                    $schedule->setMessages('Bulk transfer failed');
                }
            }
            
        } catch (\Exception $e) {
            $this->cronLogger->logRequest('Error in GridTransfer cron: ' . $e->getMessage());
            if ($schedule) {
                $schedule->setStatus(Schedule::STATUS_ERROR);
                $schedule->setMessages('Error: ' . $e->getMessage());
            }
        }
        
        $this->cronLogger->logRequest('GridTransfer cron job completed');
    }
}
