<?php

namespace Kylin\Payment\Gateways;

/**
 * Stripe支付网关
 */
class StripeGateway extends AbstractGateway
{
    /**
     * 发起支付
     */
    public function pay(array $params): mixed
    {
        // 构建支付参数
        $payParams = [
            'amount' => $params['amount'],
            'currency' => $params['currency'] ?? 'cny',
            'description' => $params['description'] ?? '',
            'source' => $params['source'] ?? '',
            'metadata' => $params['metadata'] ?? [],
            'expand' => $params['expand'] ?? []
        ];

        // 构建请求URL
        $url = $this->getApiUrl() . '/v1/charges';

        // 发起请求
        $result = $this->request($url, $payParams, 'POST', [
            'Authorization' => 'Bearer ' . $this->getConfig('secret_key'),
            'Content-Type' => 'application/x-www-form-urlencoded'
        ]);

        return $result;
    }

    /**
     * 查询订单
     */
    public function query(string $orderNo): mixed
    {
        // 构建请求URL
        $url = $this->getApiUrl() . '/v1/charges/' . $orderNo;

        // 发起请求
        $result = $this->request($url, [], 'GET', [
            'Authorization' => 'Bearer ' . $this->getConfig('secret_key')
        ]);

        return $result;
    }

    /**
     * 退款
     */
    public function refund(array $params): mixed
    {
        // 构建退款参数
        $refundParams = [
            'charge' => $params['charge_id'],
            'amount' => $params['amount'] ?? null,
            'reason' => $params['reason'] ?? null,
            'metadata' => $params['metadata'] ?? []
        ];

        // 构建请求URL
        $url = $this->getApiUrl() . '/v1/refunds';

        // 发起请求
        $result = $this->request($url, $refundParams, 'POST', [
            'Authorization' => 'Bearer ' . $this->getConfig('secret_key'),
            'Content-Type' => 'application/x-www-form-urlencoded'
        ]);

        return $result;
    }

    /**
     * 关闭订单
     */
    public function close(string $orderNo): mixed
    {
        // Stripe 不需要关闭订单，直接返回成功
        return [
            'code' => 'SUCCESS',
            'message' => '订单已关闭'
        ];
    }

    /**
     * 回调处理
     */
    public function callback(array $data): mixed
    {
        // 验证签名
        // $signature = $_SERVER['HTTP_STRIPE_SIGNATURE'];
        // $payload = @file_get_contents('php://input');
        // $event = null;
        // try {
        //     $event = \Stripe\Webhook::constructEvent(
        //         $payload,
        //         $signature,
        //         $this->getConfig('webhook_secret')
        //     );
        // } catch (\UnexpectedValueException $e) {
        //     return ['code' => 'FAIL', 'message' => '无效的payload'];
        // } catch (\Stripe\Exception\SignatureVerificationException $e) {
        //     return ['code' => 'FAIL', 'message' => '无效的签名'];
        // }

        // 处理支付结果
        $eventType = $data['type'] ?? '';
        if (in_array($eventType, ['charge.succeeded', 'payment_intent.succeeded'])) {
            // 支付成功，处理订单
            return [
                'code' => 'SUCCESS',
                'message' => '回调处理成功',
                'data' => [
                    'id' => $data['data']['object']['id'] ?? '',
                    'status' => $data['data']['object']['status'] ?? '',
                    'type' => $eventType
                ]
            ];
        } else {
            // 支付失败
            return [
                'code' => 'FAIL',
                'message' => '支付失败',
                'data' => [
                    'type' => $eventType
                ]
            ];
        }
    }

    /**
     * 获取API URL
     */
    protected function getApiUrl(): string
    {
        return 'https://api.stripe.com';
    }
}
