<?php

namespace Kylin\Ecommerce;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class EcommerceManager
{
    /**
     * 计算订单金额（含优惠）
     */
    public function calculateOrderAmount(array $items, ?int $couponId = null): array
    {
        $totalAmount = collect($items)->sum(fn ($item) => $item['price'] * $item['quantity']);
        $discountAmount = 0;

        if ($couponId) {
            $discountAmount = $this->calculateCouponDiscount($couponId, $totalAmount);
        }

        return [
            'total_amount' => round($totalAmount, 2),
            'discount_amount' => round($discountAmount, 2),
            'pay_amount' => round(max(0, $totalAmount - $discountAmount), 2),
        ];
    }

    /**
     * 计算优惠券折扣
     */
    public function calculateCouponDiscount(int $couponId, float $orderAmount): float
    {
        $coupon = Cache::remember("coupon:{$couponId}", now()->addMinutes(10), function () use ($couponId) {
            return \App\Models\Coupon::find($couponId);
        });

        if (!$coupon || !$coupon->isAvailable()) {
            return 0;
        }

        if ($coupon->min_amount && $orderAmount < $coupon->min_amount) {
            return 0;
        }

        return match ($coupon->type->value) {
            1 => min($coupon->value, $orderAmount),           // 满减
            2 => round($orderAmount * (1 - $coupon->value / 10), 2), // 折扣
            3 => min($coupon->value, $orderAmount),           // 无门槛
            default => 0,
        };
    }

    /**
     * 扣减库存（乐观锁）
     */
    public function deductStock(int $productId, ?int $specId, int $quantity): bool
    {
        return DB::transaction(function () use ($productId, $specId, $quantity) {
            if ($specId) {
                $affected = DB::table('product_specs')
                    ->where('id', $specId)
                    ->where('stock', '>=', $quantity)
                    ->decrement('stock', $quantity);

                if ($affected === 0) {
                    return false;
                }
            }

            $affected = DB::table('products')
                ->where('id', $productId)
                ->where('stock', '>=', $quantity)
                ->decrement('stock', $quantity);

            if ($affected === 0) {
                throw new \Exception('库存不足');
            }

            DB::table('products')->where('id', $productId)->increment('sales', $quantity);

            return true;
        });
    }

    /**
     * 生成订单号
     */
    public function generateOrderNo(): string
    {
        return 'EC' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
    }

    /**
     * 获取库存预警商品
     */
    public function getLowStockProducts(int $threshold = 10): \Illuminate\Support\Collection
    {
        return Cache::remember('low_stock_products', now()->addMinutes(5), function () use ($threshold) {
            return \App\Models\Product::where('stock', '<=', $threshold)
                ->where('status', 1)
                ->get(['id', 'name', 'stock', 'sku']);
        });
    }
}
