<?php

namespace Database\Factories;

use App\Models\Transaction;
use App\Models\User;
use App\Models\Wallet;
use App\Models\BillService;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class TransactionFactory extends Factory
{
    protected $model = Transaction::class;

    public function definition(): array
    {
        $amount = fake()->randomFloat(2, 100, 50000);
        $fee = 50;

        return [
            'reference' => 'TXN-' . strtoupper(Str::random(4)) . '-' . now()->format('YmdHis'),
            'type' => fake()->randomElement(['airtime', 'data', 'cable', 'electricity', 'exam_pin']),
            'service_name' => fake()->words(3, true),
            'network' => fake()->randomElement(['mtn', 'airtel', 'glo', '9mobile']),
            'customer_number' => fake()->numerify('080########'),
            'amount' => $amount,
            'fee' => $fee,
            'total_amount' => $amount + $fee,
            'wallet_balance_before' => 10000,
            'wallet_balance_after' => 10000 - ($amount + $fee),
            'status' => fake()->randomElement(['pending', 'successful', 'failed']),
            'ip_address' => fake()->ipv4(),
            'created_at' => fake()->dateTimeBetween('-30 days', 'now'),
        ];
    }

    public function forUser(User $user): static
    {
        $wallet = $user->wallet ?? Wallet::where('user_id', $user->id)->first();

        return $this->state([
            'user_id' => $user->id,
            'wallet_id' => $wallet?->id,
        ]);
    }

    public function successful(): static
    {
        return $this->state(fn (array $attributes) => ['status' => 'successful']);
    }

    public function pending(): static
    {
        return $this->state(fn (array $attributes) => ['status' => 'pending']);
    }

    public function failed(): static
    {
        return $this->state(fn (array $attributes) => ['status' => 'failed']);
    }
}
