<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\User;
use App\Models\Messenger\Conversation;
use App\Models\Messenger\Message;
use Illuminate\Support\Facades\DB;

class MessengerSeeder extends Seeder
{
    public function run(): void
    {
        DB::transaction(function () {
            // Create test users if they don't exist
            $users = User::take(5)->get();
            if ($users->count() < 5) {
                $users = User::factory(5)->create();
            }

            // Create a DM conversation
            $dmConversation = Conversation::create([
                'type' => 'dm',
                'created_by' => $users[0]->id,
                'last_activity_at' => now(),
            ]);

            $dmConversation->addParticipant($users[0]->id, 'member');
            $dmConversation->addParticipant($users[1]->id, 'member');

            // Create some messages in the DM
            for ($i = 0; $i < 10; $i++) {
                $message = Message::create([
                    'conversation_id' => $dmConversation->id,
                    'user_id' => $users[$i % 2]->id,
                    'type' => 'text',
                    'content' => "Test message " . ($i + 1) . " in DM conversation",
                    'client_generated_id' => uniqid($users[$i % 2]->id . '_', true),
                    'created_at' => now()->subMinutes(60 - ($i * 5)),
                ]);

                // Mark messages as delivered for both participants
                $message->markAsDelivered($users[0]->id);
                $message->markAsDelivered($users[1]->id);

                // Mark some as seen
                if ($i < 7) {
                    $message->markAsSeen($users[($i + 1) % 2]->id);
                }
            }

            // Update last message
            $dmConversation->update(['last_message_id' => $message->id]);

            // Create a group conversation
            $groupConversation = Conversation::create([
                'type' => 'group',
                'title' => 'Test Group Chat',
                'description' => 'This is a test group conversation',
                'created_by' => $users[0]->id,
                'last_activity_at' => now(),
                'settings' => [
                    'join_approval_required' => false,
                    'message_retention_days' => 30,
                ],
            ]);

            // Add participants to group
            $groupConversation->addParticipant($users[0]->id, 'owner');
            $groupConversation->addParticipant($users[1]->id, 'admin');
            $groupConversation->addParticipant($users[2]->id, 'member');
            $groupConversation->addParticipant($users[3]->id, 'member');

            // Create system message for group creation
            $systemMessage = Message::createSystemMessage(
                $groupConversation->id,
                'Group was created',
                ['action' => 'group_created', 'created_by' => $users[0]->id]
            );

            // Create some messages in the group
            for ($i = 0; $i < 15; $i++) {
                $senderId = $users[$i % 4]->id;
                $message = Message::create([
                    'conversation_id' => $groupConversation->id,
                    'user_id' => $senderId,
                    'type' => 'text',
                    'content' => "Group message " . ($i + 1) . " from user " . ($i % 4 + 1),
                    'client_generated_id' => uniqid($senderId . '_', true),
                    'created_at' => now()->subMinutes(45 - ($i * 2)),
                ]);

                // Mark messages as delivered for all participants except sender
                foreach ($users->take(4) as $user) {
                    if ($user->id !== $senderId) {
                        $message->markAsDelivered($user->id);
                        
                        // Mark some as seen (not all users have seen all messages)
                        if (rand(1, 100) <= 70) { // 70% chance of being seen
                            $message->markAsSeen($user->id);
                        }
                    }
                }
            }

            // Update last message
            $groupConversation->update(['last_message_id' => $message->id]);

            $this->command->info('Messenger seeder completed successfully!');
            $this->command->info("Created DM conversation with ID: {$dmConversation->id}");
            $this->command->info("Created group conversation with ID: {$groupConversation->id}");
        });
    }
}
