<?php

namespace Kylin\Payment\Gateways;

use Kylin\Payment\Contracts\GatewayInterface;

/**
 * 支付网关抽象基类
 */
abstract class AbstractGateway implements GatewayInterface
{
    /**
     * 沙盒模式
     */
    protected bool $sandbox = false;

    /**
     * 构造函数
     */
    public function __construct(
        protected readonly array $config
    ) {
        $this->sandbox = $config['sandbox'] ?? false;
    }

    /**
     * 设置沙盒模式
     */
    public function setSandbox(bool $sandbox): self
    {
        $this->sandbox = $sandbox;
        return $this;
    }

    /**
     * 获取沙盒模式状态
     */
    public function getSandbox(): bool
    {
        return $this->sandbox;
    }

    /**
     * 获取配置
     */
    public function getConfig(string $key, mixed $default = null): mixed
    {
        return $this->config[$key] ?? $default;
    }

    /**
     * 生成随机字符串
     */
    protected function generateNonceStr(int $length = 32): string
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }

    /**
     * 发起HTTP请求
     */
    protected function request(string $url, array $params = [], string $method = 'POST'): array
    {
        // 实际项目中需要实现HTTP请求
        // 这里仅做示例
        return ['code' => 'SUCCESS', 'message' => '请求成功'];
    }
}
