<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Invoice;
use App\Models\WalletTransaction;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class CancelOldInvoices extends Command
{
    protected $signature = 'invoices:cancel-old';
    protected $description = 'لغو فاکتورهای پرداخت‌نشده بعد از ۴۸ ساعت';

    public function handle()
    {
        $now = Carbon::now();
        $expirationTime = $now->subHours(48);

        // ✅ فقط pending فاکتورها
        $unPaidInvoices = Invoice::where('status', 'pending')
            ->where('created_at', '<', $expirationTime)
            ->lockForUpdate()
            ->get();

        $canceledCount = 0;

        foreach ($unPaidInvoices as $invoice) {
            DB::beginTransaction();
            try {
                // ✅ دوباره چک کن - شاید paid شده
                $invoice->refresh();
                if ($invoice->status !== 'pending') {
                    Log::warning('⚠️ Invoice is no longer pending - SKIP', [
                        'invoice_id' => $invoice->id,
                        'current_status' => $invoice->status
                    ]);
                    DB::rollBack();
                    continue;
                }

                // ✅ جستجو برای تراکنش deposit شده (یا invoice_id یا ref_id)
                $depositTransaction = WalletTransaction::where(function($q) use ($invoice) {
                    $q->where('invoice_id', $invoice->id)
                      ->orWhere(function($q2) use ($invoice) {
                          $q2->where('ref_type', 'invoice')
                            ->where('ref_id', $invoice->id);
                      });
                })
                ->where('type', 'deposit')
                ->where('status', 'completed')
                ->first();

                // ✅ اگر پول واقعاً کسر شده بود، برگردان
                if ($depositTransaction) {
                    // چک کن ببین قبلاً refund شده یا نه
                    $existingRefund = WalletTransaction::where('ref_type', 'invoice')
                        ->where('ref_id', $invoice->id)
                        ->where('type', 'refund')
                        ->where('status', 'completed')
                        ->exists();

                    if (!$existingRefund && $invoice->user_id && $invoice->amount > 0) {
                        // ایجاد تراکنش refund
                        WalletTransaction::create([
                            'user_id' => $invoice->user_id,
                            'amount' => $invoice->amount,
                            'type' => 'refund',
                            'status' => 'completed',
                            'description' => "بازگرداندن هزینه فاکتور #{$invoice->id} (منقضی شده)",
                            'invoice_id' => $invoice->id,
                            'ref_type' => 'invoice',
                            'ref_id' => $invoice->id,
                            'balance_before' => $depositTransaction->balance_after,
                            'balance_after' => $depositTransaction->balance_after + $invoice->amount,
                            'metadata' => ['canceled_reason' => 'expired', 'original_transaction_id' => $depositTransaction->id],
                        ]);

                        // بروز رسانی موجودی کاربر
                        $invoice->user->increment('wallet_balance', $invoice->amount);

                        Log::info('💰 Refund processed for expired invoice', [
                            'invoice_id' => $invoice->id,
                            'user_id' => $invoice->user_id,
                            'amount' => $invoice->amount,
                            'original_transaction_id' => $depositTransaction->id,
                        ]);
                    }
                }

                // لغو فاکتور
                $invoice->update(['status' => 'canceled']);
                $canceledCount++;

                DB::commit();

                Log::info('🗑️ Invoice Canceled Successfully', [
                    'invoice_id' => $invoice->id,
                    'user_id' => $invoice->user_id,
                    'amount' => $invoice->amount,
                    'created_at' => $invoice->created_at,
                ]);

            } catch (\Exception $e) {
                DB::rollBack();
                Log::error('❌ Error canceling invoice', [
                    'invoice_id' => $invoice->id,
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString()
                ]);
            }
        }

        $this->info("✅ تعداد {$canceledCount} فاکتور منقضی لغو شد.");
    }
}