<?php

declare(strict_types=1);

namespace Autogedal\AwbRetry\Model;

use Magento\Framework\App\ResourceConnection;

class Reconciliation
{
    public function __construct(
        private readonly ResourceConnection $resourceConnection,
        private readonly AwbErrorLogManager $errorLogManager
    ) {
    }

    public function getCandidates(?int $limit = null): array
    {
        $connection = $this->resourceConnection->getConnection();
        $select = $connection->select()
            ->from(
                ['log' => $this->resourceConnection->getTableName('autogedal_awb_error_log')],
                ['entity_id', 'awb_id', 'carrier_id']
            )
            ->joinInner(
                ['awb' => $this->resourceConnection->getTableName('eadesign_awb')],
                'awb.entity_id = log.awb_id AND awb.carrier_id = log.carrier_id AND awb.order_id = log.order_id',
                ['awb_number']
            )
            ->where('log.status <> ?', 'resolved')
            ->where('awb.status = ?', 1)
            ->where('TRIM(awb.awb_number) <> ?', '')
            ->order('log.entity_id ASC');

        if ($limit !== null) {
            $select->limit($limit);
        }

        return $connection->fetchAll($select);
    }

    public function resolve(array $candidate): bool
    {
        return $this->errorLogManager->resolveForAwb(
            (int) $candidate['awb_id'],
            (int) $candidate['carrier_id'],
            (string) $candidate['awb_number']
        );
    }
}
