<?php

namespace App\Services\Monetization;

use App\Models\Setting;
use App\Modules\Users\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

/**
 * استبدال نقاط مدار برسائل AI إضافية (رصيد ai_message_credits).
 */
final class PointsRedemptionService
{
    /**
     * @return array{points_spent: int, credits_added: int, new_balance_points: int, new_ai_credits: int}
     */
    public function redeemAiMessagePack(User $user): array
    {
        $settings = Setting::current();
        $cost = (int) $settings->points_per_ai_message_pack;
        $pack = (int) $settings->ai_messages_per_point_pack;

        if ($cost <= 0 || $pack <= 0) {
            throw ValidationException::withMessages([
                'points' => ['استبدال النقاط غير مفعّل حالياً.'],
            ]);
        }

        return DB::transaction(function () use ($user, $cost, $pack) {
            /** @var User $locked */
            $locked = User::query()->whereKey($user->id)->lockForUpdate()->firstOrFail();
            $points = (int) $locked->reward_points;

            if ($points < $cost) {
                throw ValidationException::withMessages([
                    'points' => ['رصيد النقاط غير كافٍ لهذا الاستبدال.'],
                ]);
            }

            $locked->decrement('reward_points', $cost);
            $locked->increment('ai_message_credits', $pack);
            $locked->refresh();

            return [
                'points_spent' => $cost,
                'credits_added' => $pack,
                'new_balance_points' => (int) $locked->reward_points,
                'new_ai_credits' => (int) $locked->ai_message_credits,
            ];
        });
    }
}
