<?php

namespace Kylin\Payment\Scenarios;

use Kylin\Payment\Payment;

/**
 * 分期付款场景类
 */
class InstallmentPayment
{
    /**
     * 构造函数
     */
    public function __construct(
        protected readonly string $paymentType,
        protected readonly string $name = 'default'
    ) {}

    /**
     * 发起分期付款
     */
    public function pay(array $params): mixed
    {
        // 确保参数中包含分期付款相关信息
        $params['installment'] = $params['installment'] ?? [];

        // 调用支付方法
        return Payment::pay($this->paymentType, $params, $this->name);
    }

    /**
     * 查询分期信息
     */
    public function query(string $orderNo): mixed
    {
        return Payment::query($this->paymentType, $orderNo, $this->name);
    }

    /**
     * 取消分期付款
     */
    public function cancel(string $orderNo): mixed
    {
        return Payment::close($this->paymentType, $orderNo, $this->name);
    }

    /**
     * 获取支持的分期期数
     */
    public function getSupportedPeriods(): array
    {
        // 根据支付类型返回支持的分期期数
        $periodsMap = [
            'alipay' => [3, 6, 12, 24],
            'wechat' => [3, 6, 12],
            'stripe' => [3, 6, 12, 18, 24],
        ];

        return $periodsMap[$this->paymentType] ?? [];
    }

    /**
     * 计算分期手续费
     */
    public function calculateFee(float $amount, int $period): float
    {
        // 根据支付类型和分期期数计算手续费
        $feeRates = [
            'alipay' => [
                3 => 0.023,
                6 => 0.045,
                12 => 0.075,
                24 => 0.15,
            ],
            'wechat' => [
                3 => 0.025,
                6 => 0.045,
                12 => 0.08,
            ],
            'stripe' => [
                3 => 0.04,
                6 => 0.06,
                12 => 0.1,
                18 => 0.12,
                24 => 0.14,
            ],
        ];

        $rates = $feeRates[$this->paymentType] ?? [];
        $rate = $rates[$period] ?? 0;

        return $amount * $rate;
    }
}
