<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class UserBankSeeder extends Seeder
{
    public function run(): void
    {
        // Get user and bank IDs from database
        $users = DB::table('users')->limit(5)->get();
        $banks = DB::table('banks')->limit(10)->get();

        if ($users->isEmpty() || $banks->isEmpty()) {
            return; // Skip if no users or banks exist
        }

        $userBanks = [];

        foreach ($users as $user) {
            // Add 1-2 bank accounts per user
            $numAccounts = rand(1, 2);
            $selectedBanks = $banks->random($numAccounts);

            foreach ($selectedBanks as $index => $bank) {
                $userBanks[] = [
                    'id' => (string) Str::uuid(),
                    'user_id' => $user->id,
                    'bank_id' => $bank->id,
                    'account_number' => $this->generateAccountNumber(),
                    'account_name' => $user->name ?? 'Account Holder',
                    'is_verified' => $index === 0, // First account is verified
                    'is_primary' => $index === 0, // First account is primary
                    'verification_notes' => $index === 0 ? 'Auto-verified for testing' : null,
                    'verified_at' => $index === 0 ? now() : null,
                    'created_at' => now(),
                    'updated_at' => now(),
                ];
            }
        }

        if (!empty($userBanks)) {
            DB::table('user_banks')->insert($userBanks);
        }
    }

    /**
     * Generate a realistic account number
     */
    private function generateAccountNumber(): string
    {
        // Generate 10-digit account number
        return sprintf('%010d', rand(1000000000, 9999999999));
    }
}
