<?php

namespace Fhp\Action;

use Fhp\Model\SEPAAccount;
use Fhp\PaginateableAction;
use Fhp\Protocol\BPD;
use Fhp\Protocol\Message;
use Fhp\Protocol\UPD;
use Fhp\Segment\Common\Kti;
use Fhp\Segment\KAA\HIKAA;
use Fhp\Segment\KAA\HIKAASv1;
use Fhp\Segment\KAA\HKKAAv1;
use Fhp\Segment\KAA\HKKAAv2;
use Fhp\Segment\HIRMS\Rueckmeldungscode;
use Fhp\UnsupportedException;

/**
 * Retrieves PDF bank statements from bank archive (Kontoauszug aus Archiv) via HKKAA.
 *
 * This is an alternative to HKEKP for banks that store statements in an archive/mailbox
 * instead of providing direct PDF generation.
 */
class GetStatementFromArchive extends PaginateableAction
{
    // PDF Format code
    public const FORMAT_PDF = 4;
    public const FORMAT_MT940 = 1;

    /** @var SEPAAccount */
    private $account;

    /** @var int Format to request (default: PDF = 4) */
    private $format;

    /** @var string|null Optional: from date YYYYMMDD */
    private $fromDate;

    /** @var string|null Optional: to date YYYYMMDD */
    private $toDate;

    // Response data
    /** @var string Raw PDF data (may be from multiple pages) */
    private $pdfData = '';

    /** @var array Statement metadata from response */
    private $statementInfo = [];

    /**
     * @param SEPAAccount $account The account to get statements for
     * @param int $format Format code (4 = PDF)
     * @param \DateTime|null $fromDate Optional: Start date for statement range
     * @param \DateTime|null $toDate Optional: End date for statement range
     * @return GetStatementFromArchive
     */
    public static function create(
        SEPAAccount $account,
        int $format = self::FORMAT_PDF,
        ?\DateTime $fromDate = null,
        ?\DateTime $toDate = null
    ): GetStatementFromArchive {
        $result = new GetStatementFromArchive();
        $result->account = $account;
        $result->format = $format;
        $result->fromDate = $fromDate ? $fromDate->format('Ymd') : null;
        $result->toDate = $toDate ? $toDate->format('Ymd') : null;
        return $result;
    }

    public function __serialize(): array
    {
        return [
            parent::__serialize(),
            $this->account,
            $this->format,
            $this->fromDate,
            $this->toDate,
        ];
    }

    public function __unserialize(array $serialized): void
    {
        list(
            $parentSerialized,
            $this->account,
            $this->format,
            $this->fromDate,
            $this->toDate
        ) = $serialized;

        is_array($parentSerialized)
            ? parent::__unserialize($parentSerialized)
            : parent::unserialize($parentSerialized);
    }

    /**
     * @return string The raw PDF data
     */
    public function getPdfData(): string
    {
        $this->ensureDone();
        return $this->pdfData;
    }

    /**
     * @return array Statement metadata (number, year, iban, date, filename)
     */
    public function getStatementInfo(): array
    {
        $this->ensureDone();
        return $this->statementInfo;
    }

    /**
     * @return bool Whether receipt confirmation is needed
     */
    public function needsReceipt(): bool
    {
        $this->ensureDone();
        return !empty($this->statementInfo['receiptCode']);
    }

    /** {@inheritdoc} */
    protected function createRequest(BPD $bpd, ?UPD $upd)
    {
        /** @var HIKAASv1|null $hikaas */
        $hikaas = $bpd->getLatestSupportedParameters('HIKAAS');

        if ($hikaas === null) {
            throw new UnsupportedException('The bank does not support archive statements (HKKAA).');
        }

        $param = $hikaas->getParameter();

        // Check if PDF format is supported
        if ($this->format === self::FORMAT_PDF && !$param->supportsPdf()) {
            throw new UnsupportedException('The bank does not support PDF format for archive statements.');
        }

        // Check if date range queries are supported
        if (($this->fromDate !== null || $this->toDate !== null) && !$param->canFetchByDateRange()) {
            throw new UnsupportedException('The bank does not support date range queries for archive statements.');
        }

        // Use the correct HKKAA version based on HIKAAS version in BPD
        $hikaasVersion = $hikaas->getVersion();

        // Use Kti with IBAN/BIC only (not the full account details)
        $kti = Kti::create($this->account->getIban(), $this->account->getBic());

        if ($hikaasVersion >= 2) {
            return HKKAAv2::create($kti, $this->format, $this->fromDate, $this->toDate);
        } else {
            return HKKAAv1::create($kti, $this->format, $this->fromDate, $this->toDate);
        }
    }

    /** {@inheritdoc} */
    public function processResponse(Message $response)
    {
        parent::processResponse($response);

        // Check if no statements available
        if ($response->findRueckmeldung(Rueckmeldungscode::NICHT_VERFUEGBAR) !== null) {
            return;
        }

        /** @var HIKAA[] $responseSegments */
        $responseSegments = $response->findSegments(HIKAA::class);

        if (empty($responseSegments)) {
            // No segments but also no error = empty response
            return;
        }

        foreach ($responseSegments as $hikaa) {
            // Append PDF data (for pagination)
            $this->pdfData .= $hikaa->getPdfData();

            // Store metadata from first segment
            if (empty($this->statementInfo)) {
                $this->statementInfo = [
                    'statementNumber' => $hikaa->getStatementNumber(),
                    'statementYear' => $hikaa->getStatementYear(),
                    'iban' => $hikaa->getIban(),
                    'creationDate' => $hikaa->getCreationDate(),
                    'filename' => $hikaa->getFilename(),
                    'format' => $hikaa->getFormat(),
                    'receiptCode' => $hikaa->needsReceipt() ? $hikaa->getReceiptCode() : null,
                ];
            }
        }
    }
}
