<?php

declare(strict_types=1);

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\ImpersonationLog>
 */
final class ImpersonationLogFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        $startTime = $this->faker->dateTimeBetween('-1 month', 'now');
        $endTime = $this->faker->optional(0.3)->dateTimeBetween($startTime, '+30 minutes');

        return [
            'admin_id' => User::factory()->superAdmin(),
            'target_user_id' => User::factory()->normalUser(),
            'start_time' => $startTime,
            'end_time' => $endTime,
            'ip_address' => $this->faker->ipv4(),
            'user_agent' => $this->faker->userAgent(),
            'status' => $endTime ? 'completed' : 'active',
            'pages_visited' => $this->faker->optional(0.7)->randomElements([
                '/dashboard',
                '/profile',
                '/settings',
                '/emails',
                '/reports',
            ], $this->faker->numberBetween(1, 5)),
            'actions_taken' => $this->faker->optional(0.5)->randomElements([
                'viewed_profile',
                'updated_settings',
                'downloaded_report',
                'sent_email',
                'deleted_item',
            ], $this->faker->numberBetween(1, 3)),
        ];
    }

    /**
     * Indicate that the impersonation is currently active.
     */
    public function active(): static
    {
        return $this->state(fn (array $attributes) => [
            'start_time' => now()->subMinutes($this->faker->numberBetween(1, 25)),
            'end_time' => null,
            'status' => 'active',
        ]);
    }

    /**
     * Indicate that the impersonation was completed.
     */
    public function completed(): static
    {
        return $this->state(fn (array $attributes) => [
            'end_time' => $this->faker->dateTimeBetween($attributes['start_time'], '+30 minutes'),
            'status' => 'completed',
        ]);
    }

    /**
     * Indicate that the impersonation was force terminated.
     */
    public function forceTerminated(): static
    {
        return $this->state(fn (array $attributes) => [
            'end_time' => $this->faker->dateTimeBetween($attributes['start_time'], '+30 minutes'),
            'status' => 'force_terminated',
        ]);
    }

    /**
     * Indicate that the impersonation expired.
     */
    public function expired(): static
    {
        return $this->state(fn (array $attributes) => [
            'start_time' => now()->subMinutes(35),
            'end_time' => now()->subMinutes(5),
            'status' => 'expired',
        ]);
    }
}
