<?php

namespace Lightscale\LaralightAccessLog\Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class AccessLogFactory extends Factory
{
    public function modelName()
    {
        return config('access_log.model');
    }

    protected static function fakeUri(
        int $maxSegments = 2,
        int $maxWords = 3,
    ): string
    {
        $segsAmount = fake()->numberBetween(0, $maxSegments);

        $segs = [];
        for ($i = 0; $i < $segsAmount; $i++) {
            $wordsAmount = fake()->numberBetween(1, $maxWords);
            $segs[] = fake()->slug($wordsAmount, false);
        }

        return '/' . implode('/', $segs);
    }

    public function definition(): array
    {
        return [
            'method' => 'GET',
            'path' => static::fakeUri(),
            'status' => 200,
        ];
    }

    public function fakePath(
        int $maxSegments = 2,
        int $maxWords = 3
    ): static
    {
        return $this->state(fn() => [
            'path' => static::fakeUri($maxSegments, $maxWords)
        ]);
    }

    protected static function makeRoute(string $name, mixed $params = []): string
    {
        return route($name, $params, false);
    }

    public function path(callable|string $path): static
    {
        return $this->state(fn($state) => [
            'path' => is_callable($path) ? $path($state) : $path
        ]);
    }

    public function route(callable|string $name, mixed $params = []): static
    {
        return $this->path(
            is_callable($name) ?
            fn($state) => static::makeRoute(...$name($state)) :
            static::makeRoute($name, $params)
        );
    }

    public function paths(array $paths, bool $random = false): static
    {
        return $this->sequence(
            $random ?
            fn() => ['path' => $paths[array_rand($paths)]] :
            array_map(fn($p) => ['path' => $p], $paths)
        );
    }

    public function routes(array $routes, bool $random = false): static
    {
        return $this->paths(
            array_map(fn($r) => static::makeRoute($r[0], $r[1]), $routes),
            $random
        );
    }

    public function properties(callable|array $props): static
    {
        return $this->state(fn($state) => [
            'properties' => is_callable($props) ? $props($state) : $props
        ]);
    }

}