<?php

namespace Kylin\Payment\Services;

use Illuminate\Contracts\Container\Container;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;

/**
 * 配置缓存服务类
 */
class ConfigCacheService
{
    /**
     * 缓存前缀
     */
    protected string $prefix = 'kylin-payment:config:';

    /**
     * 缓存过期时间（分钟）
     */
    protected int $expireMinutes = 60;

    /**
     * 构造函数
     */
    public function __construct(
        protected readonly Container $app
    ) {
    }

    /**
     * 获取支付配置
     */
    public function getPaymentConfig(string $type, string $name = 'default', bool $fresh = false): array
    {
        $cacheKey = $this->getCacheKey($type, $name);

        if ($fresh) {
            $config = $this->loadConfig($type, $name);
            $this->setCache($cacheKey, $config);
            return $config;
        }

        return Cache::remember($cacheKey, $this->expireMinutes, fn () => $this->loadConfig($type, $name));
    }

    /**
     * 加载配置
     */
    protected function loadConfig(string $type, string $name = 'default'): array
    {
        $config = Config::get("payment.{$type}", []);
        return $config[$name] ?? [];
    }

    /**
     * 清除指定支付方式的配置缓存
     */
    public function clearPaymentConfig(string $type, string $name = 'default'): bool
    {
        $cacheKey = $this->getCacheKey($type, $name);
        return Cache::forget($cacheKey);
    }

    /**
     * 清除所有支付配置缓存
     */
    public function clearAllPaymentConfig(): bool
    {
        $cacheKeys = Cache::getPrefix() . $this->prefix . '*';
        return Cache::forget($cacheKeys);
    }

    /**
     * 获取缓存键
     */
    protected function getCacheKey(string $type, string $name = 'default'): string
    {
        return "{$this->prefix}{$type}:{$name}";
    }

    /**
     * 设置缓存
     */
    protected function setCache(string $key, mixed $value, ?int $minutes = null): void
    {
        $minutes ??= $this->expireMinutes;
        Cache::put($key, $value, $minutes);
    }

    /**
     * 获取所有支付类型
     */
    public function getAllPaymentTypes(bool $fresh = false): array
    {
        $cacheKey = "{$this->prefix}all_types";

        if ($fresh) {
            $types = $this->loadAllPaymentTypes();
            $this->setCache($cacheKey, $types);
            return $types;
        }

        return Cache::remember($cacheKey, $this->expireMinutes, fn () => $this->loadAllPaymentTypes());
    }

    /**
     * 加载所有支付类型
     */
    protected function loadAllPaymentTypes(): array
    {
        $config = Config::get('payment', []);
        return array_keys($config);
    }

    /**
     * 设置缓存过期时间
     */
    public function setExpireMinutes(int $minutes): self
    {
        $this->expireMinutes = $minutes;
        return $this;
    }

    /**
     * 获取缓存过期时间
     */
    public function getExpireMinutes(): int
    {
        return $this->expireMinutes;
    }
}
