<?php

namespace Kylin\Payment\Services;

use Kylin\Payment\Payment;
use Illuminate\Contracts\Container\Container;

/**
 * 支付测试工具服务类
 */
class TestToolService
{
    /**
     * 构造函数
     */
    public function __construct(
        protected readonly Container $app,
        protected readonly ConfigCacheService $configCacheService
    ) {
    }

    /**
     * 生成测试支付参数
     */
    public function generateTestParams(string $type, array $params = []): array
    {
        $defaultParams = [
            'out_trade_no' => "test_{$this->generateRandomString(8)}",
            'total_amount' => 0.01,
            'subject' => '测试商品',
            'body' => '测试商品描述',
            'return_url' => 'http://localhost/return',
            'notify_url' => 'http://localhost/notify',
        ];

        // 根据支付类型添加特定参数
        match ($type) {
            'wechat' => $defaultParams['trade_type'] = 'NATIVE',
            'alipay' => $defaultParams['product_code'] = 'FAST_INSTANT_TRADE_PAY',
            'unionpay' => [
                $defaultParams['orderId'] = $defaultParams['out_trade_no'],
                $defaultParams['txnAmt'] = 1,
                $defaultParams['currencyCode'] = '156',
                $defaultParams['txnTime'] = date('YmdHis'),
                $defaultParams['txnType'] = '01',
                $defaultParams['txnSubType'] = '01',
                $defaultParams['bizType'] = '000201',
                $defaultParams['channelType'] = '08',
            ],
            'douyin' => $defaultParams['trade_type'] = 'APP',
            'jsbank' => [
                $defaultParams['orderId'] = $defaultParams['out_trade_no'],
                $defaultParams['txnAmt'] = 1,
                $defaultParams['currencyCode'] = '156',
                $defaultParams['txnTime'] = date('YmdHis'),
            ],
            'alipay_global' => [
                $defaultParams['product_code'] = 'FAST_INSTANT_TRADE_PAY',
                $defaultParams['currency'] = 'USD',
            ],
            'paypal' => [
                $defaultParams['currency'] = 'USD',
                $defaultParams['description'] = $defaultParams['body'],
            ],
            'stripe' => [
                $defaultParams['currency'] = 'usd',
                $defaultParams['description'] = $defaultParams['body'],
            ],
            'google_pay' => $defaultParams['currency'] = 'USD',
            'apple_pay' => $defaultParams['currency'] = 'USD',
        };

        return array_merge($defaultParams, $params);
    }

    /**
     * 测试支付
     */
    public function testPay(string $type, array $params = [], string $name = 'default'): mixed
    {
        $testParams = $this->generateTestParams($type, $params);
        return Payment::pay($type, $testParams, $name);
    }

    /**
     * 测试查询
     */
    public function testQuery(string $type, string $orderNo, string $name = 'default'): mixed
    {
        return Payment::query($type, $orderNo, $name);
    }

    /**
     * 测试退款
     */
    public function testRefund(string $type, array $params = [], string $name = 'default'): mixed
    {
        $defaultRefundParams = [
            'out_refund_no' => "refund_{$this->generateRandomString(8)}",
            'refund_amount' => 0.01,
            'total_amount' => 0.01,
        ];

        $testParams = array_merge($defaultRefundParams, $params);
        return Payment::refund($type, $testParams, $name);
    }

    /**
     * 测试关闭订单
     */
    public function testClose(string $type, string $orderNo, string $name = 'default'): mixed
    {
        return Payment::close($type, $orderNo, $name);
    }

    /**
     * 测试回调
     */
    public function testCallback(string $type, array $data = [], string $name = 'default'): mixed
    {
        return Payment::callback($type, $data, $name);
    }

    /**
     * 验证配置
     */
    public function validateConfig(string $type, string $name = 'default'): array
    {
        $config = $this->configCacheService->getPaymentConfig($type, $name);

        $errors = [];

        // 验证必要配置项
        match ($type) {
            'wechat' => [
                empty($config['app_id']) && $errors[] = 'app_id is required',
                empty($config['mch_id']) && $errors[] = 'mch_id is required',
                empty($config['key']) && $errors[] = 'key is required',
            ],
            'alipay' => [
                empty($config['app_id']) && $errors[] = 'app_id is required',
                empty($config['private_key']) && $errors[] = 'private_key is required',
                empty($config['public_key']) && $errors[] = 'public_key is required',
            ],
            'unionpay' => [
                empty($config['mer_id']) && $errors[] = 'mer_id is required',
                empty($config['private_key']) && $errors[] = 'private_key is required',
                empty($config['public_key']) && $errors[] = 'public_key is required',
            ],
            'douyin' => [
                empty($config['app_id']) && $errors[] = 'app_id is required',
                empty($config['secret']) && $errors[] = 'secret is required',
            ],
            'jsbank' => [
                empty($config['mer_id']) && $errors[] = 'mer_id is required',
                empty($config['private_key']) && $errors[] = 'private_key is required',
                empty($config['public_key']) && $errors[] = 'public_key is required',
            ],
            'alipay_global' => [
                empty($config['app_id']) && $errors[] = 'app_id is required',
                empty($config['private_key']) && $errors[] = 'private_key is required',
                empty($config['public_key']) && $errors[] = 'public_key is required',
            ],
            'paypal' => [
                empty($config['client_id']) && $errors[] = 'client_id is required',
                empty($config['client_secret']) && $errors[] = 'client_secret is required',
            ],
            'stripe' => [
                empty($config['secret_key']) && $errors[] = 'secret_key is required',
                empty($config['publishable_key']) && $errors[] = 'publishable_key is required',
            ],
            'google_pay' => empty($config['merchant_id']) && $errors[] = 'merchant_id is required',
            'apple_pay' => empty($config['merchant_id']) && $errors[] = 'merchant_id is required',
        };

        return [
            'valid' => empty($errors),
            'errors' => $errors,
            'config' => $config,
        ];
    }

    /**
     * 获取测试报告
     */
    public function getTestReport(string $type, string $name = 'default'): array
    {
        $configValidation = $this->validateConfig($type, $name);

        $report = [
            'payment_type' => $type,
            'config_name' => $name,
            'config_validation' => $configValidation,
            'test_params' => $this->generateTestParams($type),
        ];

        return $report;
    }

    /**
     * 生成随机字符串
     */
    private function generateRandomString(int $length = 8): string
    {
        return date('YmdHis') . '_' . rand(1000, 9999);
    }
}
