<?php

declare(strict_types=1);

namespace App\Http\Resources;

use App\Models\BankCard;
use App\Models\WalletTransaction;
use App\Models\WithdrawalRequest;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class WalletSummaryResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $balance = (int) ($this->wallet ?? 0);

        $pendingWithdrawals = WithdrawalRequest::query()
            ->where('user_id', $this->id)
            ->where('status', WithdrawalRequest::STATUS_PENDING)
            ->get(['id', 'amount', 'status', 'created_at']);

        $pendingAmount = (int) $pendingWithdrawals->sum('amount');

        $defaultCard = BankCard::query()
            ->where('user_id', $this->id)
            ->where('is_default', true)
            ->where('status', BankCard::STATUS_ACTIVE)
            ->first();

        $cardsCount = BankCard::query()
            ->where('user_id', $this->id)
            ->where('status', BankCard::STATUS_ACTIVE)
            ->count();

        $recentTransactions = WalletTransaction::query()
            ->where('user_id', $this->id)
            ->latest()
            ->limit(5)
            ->get();

        return [
            'balance' => $balance,
            'balance_formatted' => number_format($balance),
            'available_balance' => $balance,
            'pending_withdrawal_amount' => $pendingAmount,
            'pending_withdrawals_count' => $pendingWithdrawals->count(),
            'bank_cards_count' => $cardsCount,
            'default_bank_card' => $defaultCard ? new BankCardResource($defaultCard) : null,
            'recent_transactions' => WalletTransactionResource::collection($recentTransactions),
            'actions' => [
                'can_deposit' => true,
                'can_withdraw' => $balance > 0 && $cardsCount > 0,
                'min_deposit' => 1000,
                'min_withdraw' => 10000,
            ],
        ];
    }
}
