<?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\EKA\HIEKA;
use Fhp\Segment\EKA\HIEKASv5;
use Fhp\Segment\EKA\HKEKAv5;
use Fhp\Segment\HIRMS\Rueckmeldungscode;
use Fhp\UnsupportedException;

/**
 * Retrieves electronic bank statements (Elektronischer Kontoauszug) via HKEKA.
 *
 * This supports both MT940 and PDF formats depending on what the bank offers.
 */
class GetElectronicStatement extends PaginateableAction
{
    // Format codes
    public const FORMAT_MT940 = 1;
    public const FORMAT_PDF = 2;

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

    /** @var int|null Format to request (1=MT940, 2=PDF, null=default) */
    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 data (MT940 or PDF binary) */
    private $data = '';

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

    /**
     * @param SEPAAccount $account The account to get statements for
     * @param int|null $format Format code (1=MT940, 2=PDF, null=bank default)
     * @param \DateTime|null $fromDate Optional: Start date for statement range
     * @param \DateTime|null $toDate Optional: End date for statement range
     * @return GetElectronicStatement
     */
    public static function create(
        SEPAAccount $account,
        ?int $format = null,
        ?\DateTime $fromDate = null,
        ?\DateTime $toDate = null
    ): GetElectronicStatement {
        $result = new GetElectronicStatement();
        $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 data (MT940 text or PDF binary)
     */
    public function getData(): string
    {
        $this->ensureDone();
        return $this->data;
    }

    /**
     * @return array Statement metadata (number, year, iban, date, format)
     */
    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 HIEKASv5|null $hiekas */
        $hiekas = $bpd->getLatestSupportedParameters('HIEKAS');

        if ($hiekas === null) {
            throw new UnsupportedException('The bank does not support electronic statements (HKEKA).');
        }

        $param = $hiekas->getParameter();

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

        // Use Kti (IBAN/BIC) for version 5
        $kti = Kti::fromAccount($this->account);
        return HKEKAv5::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 HIEKA[] $responseSegments */
        $responseSegments = $response->findSegments(HIEKA::class);

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

        foreach ($responseSegments as $hieka) {
            // Append data (for pagination)
            $this->data .= $hieka->getData();

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