<?php

namespace App\Http\Controllers\Shop;

use App\Http\Controllers\Controller;
use App\Models\ReservedAccount;
use App\Models\Transaction;
use App\Services\PaymentMethodService;
use App\Services\TransactionReceiptService;
use Inertia\Inertia;
use Inertia\Response;

class DashboardController extends Controller
{
    public function __invoke(TransactionReceiptService $receiptService): Response
    {
        $user = auth()->user();
        $user->loadMissing('wallet');
        $paymentMethodService = app(PaymentMethodService::class);
        $fundingMethods = $paymentMethodService->userFundingMethods($user);
        $hasReservedMethod = data_get($fundingMethods, 'monnify_reserved.available', false)
            || data_get($fundingMethods, 'paymentpoint_reserved.available', false);

        $recentTransactions = Transaction::query()
            ->with([
                'category:id,name,slug',
                'plan:id,name,network_id',
                'plan.network:id,name,slug',
                'latestVendorLog',
            ])
            ->where('user_id', $user->id)
            ->latest()
            ->limit(10)
            ->get()
            ->map(fn (Transaction $transaction): array => [
                'id' => (int) $transaction->id,
                'status' => (string) $transaction->status,
                'internal_reference' => (string) $transaction->internal_reference,
                'vendor_reference' => $transaction->vendor_reference,
                'amount_charged' => (string) $transaction->amount_charged,
                'created_at' => optional($transaction->created_at)->toDateTimeString(),
                'category' => $transaction->category ? [
                    'id' => (int) $transaction->category->id,
                    'name' => $transaction->category->name,
                    'slug' => $transaction->category->slug,
                ] : null,
                'plan' => $transaction->plan ? [
                    'id' => (int) $transaction->plan->id,
                    'name' => $transaction->plan->name,
                ] : null,
                'receipt' => $receiptService->payload($transaction),
            ])
            ->values();

        return Inertia::render('App/Dashboard', [
            'walletBalance' => $user->wallet?->balance ?? '0.00',
            'reservedAccounts' => $hasReservedMethod
                ? ReservedAccount::query()
                    ->where('user_id', $user->id)
                    ->orderByDesc('id')
                    ->get()
                : [],
            'fundingMethods' => $fundingMethods,
            'recentTransactions' => $recentTransactions,
        ]);
    }
}
