<?php

namespace Database\Seeders;

use App\Models\ChatAgent;
use App\Models\User;
use Illuminate\Database\Seeder;

/**
 * ChatAgentSeeder
 *
 * Designates the default SSHIA system administrator as the initial
 * live chat support agent. This ensures the chat support system is
 * operational immediately after a fresh installation, with at least
 * one active agent available to handle incoming member conversations.
 *
 * Additional agents can be appointed by Super Manager or Manager roles
 * through the Chat Agent management interface.
 *
 * Depends on: UserSeeder (admin user must exist)
 * Uses firstOrCreate keyed on user_id for idempotency — safe to re-run.
 */
class ChatAgentSeeder extends Seeder
{
    public function run(): void
    {
        // Locate the primary system administrator
        $admin = User::where('email', 'admin@sshia.org')->first()
            ?? User::whereHas('roles', function ($q) {
                $q->where('name', 'Super Manager');
            })->first();

        if (! $admin) {
            $this->command->warn('ChatAgentSeeder: No admin user found. Skipping chat agent creation.');
            $this->command->warn('Ensure UserSeeder has run and an admin@sshia.org user exists.');
            return;
        }

        // Avoid duplicate agent records
        $existing = ChatAgent::where('user_id', $admin->id)->withTrashed()->first();

        if ($existing) {
            $this->command->info("ChatAgentSeeder: Agent for {$admin->email} already exists. Skipping.");
            return;
        }

        ChatAgent::create([
            'user_id'              => $admin->id,
            'appointed_by'         => $admin->id,
            'categories'           => null,   // null = handles all categories
            'status'               => ChatAgent::STATUS_OFFLINE,
            'is_active'            => true,
            'max_concurrent_chats' => 5,
            'current_chats'        => 0,
            'total_conversations'  => 0,
            'avg_response_time'    => 0,
            'satisfaction_rating'  => 0,
        ]);

        $this->command->info("ChatAgentSeeder: {$admin->email} designated as default chat agent.");
    }
}
