<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Wallet;
use App\Models\WalletTransaction;
use Illuminate\Database\Seeder;

class WalletSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $users = User::all();

        foreach ($users as $user) {
            $wallet = $user->wallet;
            
            if (!$wallet) {
                continue;
            }

            // Create transaction history
            $transactionCount = rand(5, 15);
            $balance = $wallet->balance;
            
            for ($i = 0; $i < $transactionCount; $i++) {
                $type = rand(0, 1) === 0 ? 'topup' : 'payment';
                
                if ($type === 'topup') {
                    $amount = rand(20, 100);
                    $balanceBefore = $balance;
                    $balance += $amount;
                } else {
                    $amount = rand(1, 50);
                    $balanceBefore = $balance;
                    $balance = max(0, $balance - $amount);
                }
                
                WalletTransaction::create([
                    'wallet_id' => $wallet->id,
                    'user_id' => $user->id,
                    'type' => $type,
                    'amount' => $amount,
                    'balance_before' => $balanceBefore,
                    'balance_after' => $balance,
                    'status' => 'completed',
                    'reference' => strtoupper($type) . '-' . strtoupper(uniqid()),
                    'payment_method' => $type === 'topup' ? 'card' : null,
                    'description' => $type === 'topup' ? 'Wallet top-up' : 'PAYG session payment',
                    'created_at' => now()->subDays(rand(1, 30))->subHours(rand(0, 23)),
                ]);
            }
            
            // Update wallet balance
            $wallet->update(['balance' => $balance]);
        }
    }
}
