<?php

namespace Database\Factories;

use App\Enums\UserRole;
use App\Enums\UserStatus;
use App\Models\User;
use App\Support\PublicId;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

/**
 * @extends Factory<User>
 */
class UserFactory extends Factory
{
    protected static ?string $password;

    public function definition(): array
    {
        $displayName = fake()->name();
        $username = Str::lower(fake()->unique()->userName());

        return [
            'public_id' => PublicId::generate(),
            'name' => $displayName,
            'username' => $username,
            'display_name' => $displayName,
            'email' => fake()->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => static::$password ??= Hash::make('password'),
            'remember_token' => Str::random(10),
            'country_code' => 'EG',
            'preferred_locale' => 'en',
            'timezone' => 'UTC',
            'role' => UserRole::User,
            'status' => UserStatus::Active,
            'terms_accepted_at' => now(),
        ];
    }

    public function unverified(): static
    {
        return $this->state(fn (array $attributes) => [
            'email_verified_at' => null,
        ]);
    }

    public function admin(): static
    {
        return $this->state(fn (array $attributes) => [
            'role' => UserRole::Admin,
        ]);
    }

    public function superAdmin(): static
    {
        return $this->state(fn (array $attributes) => [
            'role' => UserRole::SuperAdmin,
        ]);
    }

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

    public function withPhone(string $dialCode = '20', string $number = '1001234567'): static
    {
        $digits = preg_replace('/\D+/', '', $number) ?? $number;

        return $this->state(fn (array $attributes) => [
            'phone_country_code' => $dialCode,
            'phone_number' => $digits,
            'phone_e164' => '+'.$dialCode.$digits,
        ]);
    }
}
