<?php

namespace App\Services\Payments;

use App\Models\PaymentSubmission;
use App\Models\SubscriptionPlan;
use App\Modules\Users\Models\User;
use App\Modules\Wallet\Models\WalletTransaction;
use App\Services\Subscriptions\SubscriptionLifecycleService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

/**
 * مراجعة المدفوعات اليدوية — موافقة أو رفض من المدير.
 */
final class PaymentReviewService
{
    public function __construct(
        private readonly SubscriptionLifecycleService $subscriptions,
    ) {}

    public function approve(PaymentSubmission $submission, User $admin, ?string $adminNote = null): void
    {
        if ($submission->status !== PaymentSubmission::STATUS_PENDING) {
            throw ValidationException::withMessages([
                'status' => ['تمت معالجة هذا الطلب مسبقاً.'],
            ]);
        }

        DB::transaction(function () use ($submission, $admin, $adminNote): void {
            $submission = PaymentSubmission::query()->whereKey($submission->id)->lockForUpdate()->firstOrFail();

            if ($submission->status !== PaymentSubmission::STATUS_PENDING) {
                throw ValidationException::withMessages([
                    'status' => ['تمت معالجة هذا الطلب مسبقاً.'],
                ]);
            }

            $user = User::query()->whereKey($submission->user_id)->lockForUpdate()->firstOrFail();

            if ($submission->purpose === PaymentSubmission::PURPOSE_WALLET) {
                $this->creditWallet($user, (float) $submission->amount, $submission);
            } elseif ($submission->purpose === PaymentSubmission::PURPOSE_SUBSCRIPTION) {
                $plan = SubscriptionPlan::query()->whereKey($submission->subscription_plan_id)->firstOrFail();
                $endsAt = $plan->slug !== 'free' ? now()->addMonth() : null;
                $this->subscriptions->assignPlanForUser($user, $plan, $endsAt);
            } else {
                throw ValidationException::withMessages([
                    'purpose' => ['غرض الدفع غير معروف.'],
                ]);
            }

            $submission->update([
                'status' => PaymentSubmission::STATUS_APPROVED,
                'admin_note' => $adminNote,
                'reviewed_by' => $admin->id,
                'reviewed_at' => now(),
            ]);
        });
    }

    public function reject(PaymentSubmission $submission, User $admin, ?string $adminNote = null): void
    {
        if ($submission->status !== PaymentSubmission::STATUS_PENDING) {
            throw ValidationException::withMessages([
                'status' => ['تمت معالجة هذا الطلب مسبقاً.'],
            ]);
        }

        $submission->update([
            'status' => PaymentSubmission::STATUS_REJECTED,
            'admin_note' => $adminNote,
            'reviewed_by' => $admin->id,
            'reviewed_at' => now(),
        ]);
    }

    private function creditWallet(User $user, float $amount, PaymentSubmission $submission): void
    {
        if ($amount <= 0) {
            throw ValidationException::withMessages([
                'amount' => ['المبلغ غير صالح.'],
            ]);
        }

        $current = (float) $user->wallet_balance;
        $next = round($current + $amount, 2);

        WalletTransaction::query()->create([
            'user_id' => $user->id,
            'type' => 'deposit',
            'amount' => $amount,
            'reference' => 'PAY-'.$submission->id.'-'.strtoupper(Str::random(6)),
            'description' => 'إيداع بعد موافقة الدفع #'.$submission->id,
            'status' => 'completed',
        ]);

        $user->update(['wallet_balance' => (string) $next]);
    }
}
