<?php
declare(strict_types=1);

namespace Autogedal\AutogedalHelper\Setup\Patch\Data;

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

class BackfillCouponCodeToOrderGrid implements DataPatchInterface
{
    private ModuleDataSetupInterface $moduleDataSetup;

    public function __construct(ModuleDataSetupInterface $moduleDataSetup)
    {
        $this->moduleDataSetup = $moduleDataSetup;
    }

    public function apply()
    {
        $this->moduleDataSetup->getConnection()->startSetup();

        $connection = $this->moduleDataSetup->getConnection();
        $salesOrderTable = $this->moduleDataSetup->getTable('sales_order');
        $salesOrderGridTable = $this->moduleDataSetup->getTable('sales_order_grid');

        $connection->query(
            sprintf(
                'UPDATE %s AS grid
                 INNER JOIN %s AS ord ON ord.entity_id = grid.entity_id
                 SET grid.coupon_code = ord.coupon_code
                 WHERE grid.coupon_code IS NULL OR grid.coupon_code = \'\'',
                $salesOrderGridTable,
                $salesOrderTable
            )
        );

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

        return $this;
    }

    public static function getDependencies(): array
    {
        return [];
    }

    public function getAliases(): array
    {
        return [];
    }
}
