<?php

namespace Autogedal\TbiBank\Setup\Patch\Data;

use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

/** Clear statuses backfilled onto historical and non-TBI orders by the vendor default. */
class ClearNonTbiStatuses implements DataPatchInterface
{
    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     */
    public function __construct(private ModuleDataSetupInterface $moduleDataSetup)
    {
    }

    /**
     * Clear the accidental default from non-TBI orders and their grid rows.
     */
    public function apply(): void
    {
        $this->moduleDataSetup->startSetup();

        $connection = $this->moduleDataSetup->getConnection();
        $orderTable = $this->moduleDataSetup->getTable('sales_order');
        $gridTable = $this->moduleDataSetup->getTable('sales_order_grid');
        $paymentTable = $this->moduleDataSetup->getTable('sales_order_payment');

        $connection->query(
            sprintf(
                'UPDATE %s AS so
                 SET so.tbi_status = NULL,
                     so.updated_at = so.updated_at
                 WHERE NOT EXISTS (
                     SELECT 1 FROM %s AS sop
                     WHERE sop.parent_id = so.entity_id AND sop.method = \'fusionpay\'
                 )',
                $connection->quoteIdentifier($orderTable),
                $connection->quoteIdentifier($paymentTable)
            )
        );
        $connection->query(
            sprintf(
                'UPDATE %s AS sog
                 INNER JOIN %s AS so ON so.entity_id = sog.entity_id
                 SET sog.tbi_status = NULL
                 WHERE so.tbi_status IS NULL',
                $connection->quoteIdentifier($gridTable),
                $connection->quoteIdentifier($orderTable)
            )
        );

        $this->moduleDataSetup->endSetup();
    }

    /**
     * Return no patch dependencies.
     *
     * @return string[]
     */
    public static function getDependencies(): array
    {
        return [];
    }

    /**
     * Return no patch aliases.
     *
     * @return string[]
     */
    public function getAliases(): array
    {
        return [];
    }
}
