<?php

namespace Database\Factories;

use App\Models\Event;
use App\Models\EventMember;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\EventMember>
 */
class EventMemberFactory extends Factory
{
    protected $model = EventMember::class;

    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'tenant_id' => Tenant::factory(),
            'event_id' => Event::factory(),
            'user_id' => null,
            'invited_by' => null,
            'name' => $this->faker->name(),
            'email' => $this->faker->unique()->safeEmail(),
            'role' => 'member',
            'status' => 'invited',
            'invite_token' => Str::random(32),
            'invited_at' => now(),
            'joined_at' => null,
            'last_activity_at' => null,
            'permissions' => null,
        ];
    }

    public function admin(): static
    {
        return $this->state(fn () => [
            'role' => 'tenant_admin',
            'status' => 'active',
            'joined_at' => now(),
        ]);
    }

    public function withUser(): static
    {
        return $this->state(fn (array $attributes) => [
            'user_id' => User::factory()->state([
                'role' => $attributes['role'] ?? 'member',
            ]),
            'email' => $attributes['email'] ?? $this->faker->unique()->safeEmail(),
        ]);
    }

    public function configure(): static
    {
        return $this->afterMaking(function (EventMember $member): void {
            $event = $member->event ?? Event::find($member->event_id);
            if ($event && $member->tenant_id !== $event->tenant_id) {
                $member->tenant_id = $event->tenant_id;
            }
        })->afterCreating(function (EventMember $member): void {
            $event = $member->event()->withoutGlobalScopes()->first();
            if ($event && $member->tenant_id !== $event->tenant_id) {
                $member->tenant_id = $event->tenant_id;
                $member->save();
            }
        });
    }
}
