<?php

namespace App\Services;

use App\Models\User;
use App\Models\Wallet;
use App\Models\Transaction;
use App\Models\RewardSetting;
use App\Models\UserActionCount;
use Illuminate\Support\Facades\Log;

class RewardService
{
    /**
     * Process a reward for a user action.
     *
     * @param User $user
     * @param string $actionType
     * @param int|null $referenceId
     * @param array|null $additionalData
     * @return Transaction|null
     */
    public function processReward(User $user, string $actionType, ?int $referenceId = null, ?array $additionalData = null)
    {
        try {

            // Check if the action is eligible for a reward
            if (!RewardSetting::isActionRewardable($actionType)) {
                return null;
            }
            

            // Get the reward settings
            $rewardSetting = RewardSetting::where('action_type', $actionType)
                ->where('is_active', true)
                ->first();

            if (!$rewardSetting) {
                return null;
            }

            // Check daily limit
            if (UserActionCount::hasReachedDailyLimit($user->id, $actionType, $rewardSetting->daily_limit)) {
                return null;
            }

            // Check monthly limit
            if (UserActionCount::hasReachedMonthlyLimit($user->id, $actionType, $rewardSetting->monthly_limit)) {
                return null;
            }

            // Get or create wallet
            $wallet = Wallet::firstOrCreate(
                ['user_id' => $user->id],
                [
                    'balance' => 0,
                    'pending_balance' => 0,
                    'currency' => 'USD',
                    'is_active' => true
                ]
            );

            // Increment the action count
            UserActionCount::incrementCount($user->id, $actionType);

            // Add funds to wallet
            $description = "Reward for {$actionType}" . 
                ($referenceId ? " (ID: {$referenceId})" : "");

            return $wallet->addFunds(
                $rewardSetting->reward_amount, 
                $description, 
                $actionType, 
                $referenceId, 
                $additionalData
            );
        } catch (\Exception $e) {
            Log::error('Error processing reward: ' . $e->getMessage(), [
                'user_id' => $user->id,
                'action_type' => $actionType,
                'reference_id' => $referenceId
            ]);
            
            return null;
        }
    }
} 