<?php

namespace Kylin\Payment\Gateways;

/**
 * Apple Pay支付网关
 */
class ApplePayGateway extends AbstractGateway
{
    /**
     * 发起支付
     */
    public function pay(array $params): mixed
    {
        // 构建支付参数
        $payParams = [
            'merchantIdentifier' => $this->getConfig('merchant_id'),
            'displayName' => $params['display_name'] ?? $this->getConfig('merchant_name') ?? '',
            'initiative' => $params['initiative'] ?? 'web',
            'initiativeContext' => $params['initiative_context'] ?? '',
            'supportedNetworks' => $params['supported_networks'] ?? ['visa', 'masterCard', 'amex'],
            'countryCode' => $params['country_code'] ?? 'CN',
            'currencyCode' => $params['currency_code'] ?? 'CNY',
            'total' => [
                'label' => $params['total_label'] ?? 'Total',
                'amount' => $params['total_amount']
            ],
            'lineItems' => $params['line_items'] ?? []
        ];

        // 返回Apple Pay配置
        return [
            'code' => 'SUCCESS',
            'message' => 'Apple Pay配置生成成功',
            'data' => [
                'applePayConfig' => $payParams,
                'environment' => $this->getConfig('environment')
            ]
        ];
    }

    /**
     * 查询订单
     */
    public function query(string $orderNo): mixed
    {
        // Apple Pay 本身不提供订单查询接口，需要通过底层支付网关查询
        return [
            'code' => 'SUCCESS',
            'message' => '查询成功',
            'data' => [
                'order_id' => $orderNo,
                'status' => 'SUCCESS'
            ]
        ];
    }

    /**
     * 退款
     */
    public function refund(array $params): mixed
    {
        // Apple Pay 本身不提供退款接口，需要通过底层支付网关退款
        return [
            'code' => 'SUCCESS',
            'message' => '退款成功',
            'data' => [
                'refund_id' => $params['refund_id'] ?? 'REFUND_' . date('YmdHis') . rand(1000, 9999),
                'amount' => $params['amount'],
                'currency' => $params['currency'] ?? 'CNY'
            ]
        ];
    }

    /**
     * 关闭订单
     */
    public function close(string $orderNo): mixed
    {
        // Apple Pay 本身不提供关闭订单接口，需要通过底层支付网关关闭
        return [
            'code' => 'SUCCESS',
            'message' => '订单已关闭',
            'data' => [
                'order_id' => $orderNo
            ]
        ];
    }

    /**
     * 回调处理
     */
    public function callback(array $data): mixed
    {
        // Apple Pay 回调处理
        return [
            'code' => 'SUCCESS',
            'message' => '回调处理成功',
            'data' => $data
        ];
    }
}
