<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Core\Traits\CalculatesFees;
use App\Core\Traits\GeneratesReference;
use App\Models\BillService;
use App\Models\Beneficiary;
use App\Modules\ProviderIntegration\Interfaces\ProviderInterface;
use App\Modules\Transactions\Interfaces\TransactionServiceInterface;
use App\Modules\Wallet\Interfaces\WalletServiceInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class AirtimeController extends Controller
{
    use GeneratesReference, CalculatesFees;
    public function __construct(
        protected ProviderInterface $provider,
        protected TransactionServiceInterface $transactionService,
        protected WalletServiceInterface $walletService
    ) {}

    public function index()
    {
        $networks = BillService::active()->category('airtime')->get();
        $beneficiaries = auth()->user()->beneficiaries()->type('phone')->get();

        return view('airtime.index', compact('networks', 'beneficiaries'));
    }

    public function purchase(Request $request)
    {
        $validated = $request->validate([
            'network' => ['required', 'string'],
            'phone' => ['required', 'string', 'max:20'],
            'amount' => ['required', 'numeric', 'min:50', 'max:50000'],
        ]);

        $user = $request->user();
        $service = BillService::where('code', $validated['network'])->active()->firstOrFail();
        $fee = $this->calculateFee($validated['amount'], (float) $service->service_charge);
        $totalAmount = $validated['amount'] + $fee;
        $reference = 'AIR-' . strtoupper(Str::random(8)) . '-' . now()->format('YmdHis');

        if (!$this->checkDailyTransactionLimit($user->id)) {
            $message = 'Daily transaction limit reached. Please try again tomorrow.';
            if ($request->ajax()) {
                return response()->json(['success' => false, 'message' => $message], 422);
            }
            return back()->withErrors(['amount' => $message]);
        }

        try {
            DB::beginTransaction();

            $wallet = $this->walletService->getOrCreateWallet($user->id);

            if (!$this->walletService->canDebit($user->id, $totalAmount)) {
                DB::rollBack();
                if ($request->ajax()) {
                    return response()->json(['success' => false, 'message' => 'Insufficient wallet balance'], 422);
                }
                return back()->withErrors(['amount' => 'Insufficient wallet balance']);
            }

            $transaction = $this->transactionService->createTransaction([
                'user_id' => $user->id,
                'reference' => $reference,
                'bill_service_id' => $service->id,
                'type' => 'airtime',
                'service_name' => $service->name,
                'network' => $service->code,
                'customer_number' => $validated['phone'],
                'amount' => $validated['amount'],
                'fee' => $fee,
                'total_amount' => $totalAmount,
                'ip_address' => $request->ip(),
                'device' => $request->userAgent(),
            ]);

            $this->walletService->debitWallet(
                $user->id,
                $totalAmount,
                "Airtime purchase - {$service->name}",
                $reference,
                'transaction',
                $transaction->id
            );

            $this->transactionService->markProcessing($reference);

            DB::commit();

            $requestId = self::generateVTPassRequestId();

            try {
                $response = $this->provider->purchaseAirtime(
                    $validated['phone'],
                    $validated['network'],
                    $validated['amount'],
                    $requestId
                );

                if (isset($response['code']) && $response['code'] === '000') {
                    $this->transactionService->markSuccessful($reference, $response);
                } else {
                    $this->transactionService->markFailed($reference, $response['response_description'] ?? 'Failed', $response);
                    $this->walletService->refundWallet($user->id, $totalAmount, "Refund for failed airtime purchase {$reference}", 'RFD-' . strtoupper(Str::random(8)));
                }
            } catch (\Exception $e) {
                $this->transactionService->markFailed($reference, $e->getMessage(), []);
                $this->walletService->refundWallet($user->id, $totalAmount, "Refund for failed airtime purchase {$reference}", 'RFD-' . strtoupper(Str::random(8)));
            }

            if ($request->ajax()) {
                return response()->json(['success' => true, 'message' => 'Airtime purchase submitted!', 'redirect' => route('transactions.show', $reference)]);
            }
            return redirect()->route('transactions.show', $reference)->with('success', 'Airtime purchase submitted successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            if ($request->ajax()) {
                return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
            }
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }
}
