<?php

declare(strict_types=1);

namespace App\Blog\Services;

use App\Blog\Support\PluginManager;
use App\Models\MarketPackage;
use Plugins\Neatstudio\Payment\Models\Payment;
use Plugins\Neatstudio\Payment\Services\PaymentManager;
use RuntimeException;

class MarketPurchaseService
{
    public function __construct(private PluginManager $plugins, private PaymentManager $payment)
    {
    }

    /**
     * 市场条目键：优先 item.name，缺省用下载文件名。
     */
    public function itemKey(array $item): string
    {
        $name = $item['name'] ?? null;

        if ($name) {
            return (string) $name;
        }

        return basename((string) ($item['download_url'] ?? ''), '.zip') ?: uniqid('item-');
    }

    public function itemType(array $item): string
    {
        return $item['type'] ?? 'plugin';
    }

    public function requiresPayment(array $item): bool
    {
        return (int) ($item['price'] ?? 0) > 0;
    }

    /**
     * 购买市场商品：创建订单并返回（null = 已购买过，无需重复支付）。
     */
    public function purchase(array $item): ?Payment
    {
        if (! $this->plugins->isEnabled('neatstudio.payment')) {
            throw new RuntimeException('付费市场商品需要启用支付插件');
        }

        $price = (int) ($item['price'] ?? 0);

        if ($price <= 0) {
            throw new RuntimeException('该商品免费，无需购买');
        }

        $key = $this->itemKey($item);
        $type = $this->itemType($item);
        $user = auth()->user();

        $package = MarketPackage::query()->firstOrCreate(
            ['item_key' => $key, 'item_type' => $type],
            [
                'title' => (string) ($item['title'] ?? $key),
                'price' => $price,
                'status' => 'pending',
                'user_id' => $user?->id,
            ]
        );

        if ($package->isPaid()) {
            return null;
        }

        return $this->payment->createOrder(
            $user ?? $this->systemUser(),
            '购买商品：'.$package->title,
            $price,
            $package,
            'alipay'
        );
    }

    public function isPurchased(string $key, string $type = 'plugin'): bool
    {
        return MarketPackage::query()
            ->where('item_key', $key)
            ->where('item_type', $type)
            ->where('status', 'paid')
            ->exists();
    }

    /**
     * 校验市场条目可否安装：免费直接装，付费需已购买。
     */
    public function assertCanInstall(array $item): void
    {
        if ($this->requiresPayment($item) && ! $this->isPurchased($this->itemKey($item), $this->itemType($item))) {
            throw new RuntimeException('该商品为付费商品，请先购买后再安装');
        }
    }

    private function systemUser(): \App\Models\User
    {
        $user = \App\Models\User::query()->first();

        if (! $user) {
            throw new RuntimeException('无可用用户创建订单，请先登录');
        }

        return $user;
    }
}
