<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Setup\Patch\Data;

use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Psr\Log\LoggerInterface;

/**
 * Data patch to fix existing pending sync status records
 * Updates records that have simplyin_order_id but status is still 'pending' to 'synced'
 */
class FixPendingSyncStatus implements DataPatchInterface
{
    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     * @param LoggerInterface $logger
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        LoggerInterface $logger
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->logger = $logger;
    }

    /**
     * @inheritdoc
     */
    public function apply()
    {
        $this->moduleDataSetup->startSetup();

        try {
            $connection = $this->moduleDataSetup->getConnection();
            $tableName = $this->moduleDataSetup->getTable('simplyin_order_sync');

            // Update records that have simplyin_order_id but status is 'pending'
            $updated = $connection->update(
                $tableName,
                [
                    'sync_status' => 'synced',
                    'updated_at' => date('Y-m-d H:i:s')
                ],
                [
                    'sync_status = ?' => 'pending',
                    'simplyin_order_id IS NOT NULL',
                    'simplyin_order_id != ?' => ''
                ]
            );

            $this->logger->info('SimplyIN: Fixed pending sync status records', [
                'updated_count' => $updated
            ]);

        } catch (\Exception $e) {
            $this->logger->error('SimplyIN: Error fixing pending sync status', [
                'error' => $e->getMessage()
            ]);
        }

        $this->moduleDataSetup->endSetup();

        return $this;
    }

    /**
     * @inheritdoc
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * @inheritdoc
     */
    public function getAliases()
    {
        return [];
    }
}
