<?php

namespace App\Services;

use App\Models\Order;
use App\Models\User;

class OrderRewardService
{
    public function __construct(
        private WalletService $walletService,
        private ReferralService $referrals,
    ) {}

    public function apply(Order $order, ?User $user = null): void
    {
        $order = $order->loadMissing('items.productVariant');
        $user = $user ?: $order->user;

        if (! $user || $order->payment_status !== 'paid') {
            return;
        }

        if ($order->cashback_minor > 0 || $order->loyalty_points_earned > 0) {
            return;
        }

        $loyaltyPoints = (int) $order->items->sum(fn ($item) => ($item->productVariant?->loyalty_points ?? 0) * $item->quantity);
        $cashbackMinor = (int) floor($order->items->sum(function ($item) {
            return $item->total_minor * ($item->productVariant?->cashback_basis_points ?? 0) / 10000;
        }));

        $order->update([
            'cashback_minor' => $cashbackMinor,
            'loyalty_points_earned' => $loyaltyPoints,
        ]);

        if ($loyaltyPoints > 0) {
            $user->increment('loyalty_points', $loyaltyPoints);
        }

        if ($cashbackMinor > 0) {
            $wallet = $this->walletService->ensureWallet($user, $order->currency_code);
            $this->walletService->credit($wallet, $cashbackMinor, 'cashback', 'Cashback for order '.$order->order_number, Order::class, $order->id, [
                'order_number' => $order->order_number,
            ]);
        }

        $this->referrals->applyFirstPaidOrderReward($order, $user);
    }
}
