<?php
declare(strict_types=1);

namespace App\Core\DTO;

final class PaymentResult
{
    private function __construct(
        public readonly bool $success,
        public readonly ?int $paymentId,
        public readonly ?int $receiptId,
        public readonly ?string $receiptNumber,
        public readonly ?string $amount,
        public readonly ?string $error,
    ) {}

    public static function ok(int $paymentId, int $receiptId, string $receiptNumber, string $amount): self
    {
        return new self(true, $paymentId, $receiptId, $receiptNumber, $amount, null);
    }

    public static function fail(string $error): self
    {
        return new self(false, null, null, null, null, $error);
    }

    public static function fromArray(array $data): self
    {
        if ($data['success'] ?? false) {
            return self::ok(
                (int) $data['payment_id'],
                (int) $data['receipt_id'],
                (string) $data['receipt_number'],
                (string) ($data['amount'] ?? '0.00'),
            );
        }

        return self::fail((string) ($data['error'] ?? 'Unknown error'));
    }

    public function toArray(): array
    {
        if ($this->success) {
            return [
                'success' => true,
                'payment_id' => $this->paymentId,
                'receipt_id' => $this->receiptId,
                'receipt_number' => $this->receiptNumber,
                'amount' => $this->amount,
            ];
        }

        return [
            'success' => false,
            'error' => $this->error,
        ];
    }
}
