<?php

namespace App\Services;

class PayloadParser
{
    /**
     * Extract reff_no/bill_no from gateway payload.
     */
    public static function extractReffNo(string $provider, array $payload): ?string
    {
        return match ($provider) {
            'singapay' => self::extractSingaPay($payload),
            'faspay' => self::extractFaspay($payload),
            default => null,
        };
    }

    public static function parsePrefix(?string $reffNo): ?string
    {
        if (empty($reffNo)) {
            return null;
        }

        // Prefer hyphen split: SC-123-... → SC
        if (str_contains($reffNo, '-')) {
            return strtoupper(explode('-', $reffNo, 2)[0]);
        }

        // Legacy SingaPay: RC65F3A1B2 → RC (alpha prefix before digits)
        if (preg_match('/^([A-Za-z]+)/', $reffNo, $m)) {
            return strtoupper($m[1]);
        }

        return null;
    }

    private static function extractSingaPay(array $payload): ?string
    {
        // Payment Link webhook (data.payment.additional_info.payment_link.reff_no)
        $candidates = [
            data_get($payload, 'data.payment.additional_info.payment_link.reff_no'),
            data_get($payload, 'data.transaction.reff_no'),
            data_get($payload, 'data.reff_no'),
            data_get($payload, 'reff_no'),
            data_get($payload, 'data.payment.reff_no'),
        ];

        foreach ($candidates as $value) {
            if (!empty($value)) {
                return (string) $value;
            }
        }

        return null;
    }

    private static function extractFaspay(array $payload): ?string
    {
        $candidates = [
            data_get($payload, 'bill_no'),
            data_get($payload, 'data.bill_no'),
            data_get($payload, 'response.bill_no'),
        ];

        foreach ($candidates as $value) {
            if (!empty($value)) {
                return (string) $value;
            }
        }

        return null;
    }
}
