<?php

namespace Database\Factories;

use App\Domains\Tenancy\Models\Branch;
use App\Domains\Tenancy\Models\Tenant;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

/**
 * @extends Factory<User>
 */
class UserFactory extends Factory
{
    /**
     * The current password being used by the factory.
     */
    protected static ?string $password;

    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        $company = fake()->company();
        $tenant = Tenant::query()->create([
            'company_name' => $company,
            'slug' => Str::slug($company).'-'.Str::lower(Str::random(6)),
            'currency_code' => 'USD',
            'timezone' => 'UTC',
            'status' => 'trial',
            'trial_ends_at' => now()->addDays(14),
        ]);

        $branch = Branch::query()->create([
            'tenant_id' => $tenant->getKey(),
            'name' => 'Main Branch',
            'code' => 'MAIN',
            'is_active' => true,
        ]);

        return [
            'tenant_id' => $tenant->getKey(),
            'branch_id' => $branch->getKey(),
            'full_name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'phone' => fake()->phoneNumber(),
            'status' => 'active',
            'email_verified_at' => now(),
            'password' => static::$password ??= Hash::make('password'),
            'last_login_at' => now(),
            'remember_token' => Str::random(10),
        ];
    }

    /**
     * Indicate that the model's email address should be unverified.
     */
    public function unverified(): static
    {
        return $this->state(fn (array $attributes) => [
            'email_verified_at' => null,
        ]);
    }
}
