<?php

namespace Database\Factories\Messenger;

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

class ConversationFactory extends Factory
{
    protected $model = Conversation::class;

    public function definition(): array
    {
        return [
            'type' => $this->faker->randomElement(['dm', 'group']),
            'title' => $this->faker->optional(0.7)->sentence(3),
            'description' => $this->faker->optional(0.5)->paragraph(),
            'created_by' => User::factory(),
            'last_activity_at' => $this->faker->dateTimeBetween('-1 month', 'now'),
            'is_archived' => $this->faker->boolean(10), // 10% chance of being archived
            'settings' => $this->faker->optional(0.3)->randomElements([
                'join_approval_required' => $this->faker->boolean(),
                'message_retention_days' => $this->faker->numberBetween(1, 365),
            ]),
        ];
    }

    public function directMessage(): static
    {
        return $this->state(fn (array $attributes) => [
            'type' => 'dm',
            'title' => null,
            'description' => null,
            'settings' => null,
        ]);
    }

    public function group(): static
    {
        return $this->state(fn (array $attributes) => [
            'type' => 'group',
            'title' => $this->faker->sentence(3),
        ]);
    }

    public function withParticipants(int $count = 2): static
    {
        return $this->afterCreating(function (Conversation $conversation) use ($count) {
            $users = User::factory($count)->create();
            
            foreach ($users as $index => $user) {
                $conversation->addParticipant(
                    $user->id,
                    $index === 0 && $conversation->type === 'group' ? 'owner' : 'member'
                );
            }
        });
    }
}
