<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     * Creates the chat_agents table for tracking chat agent appointments.
     * 
     * Requirements: 4.1
     */
    public function up(): void
    {
        Schema::create('chat_agents', function (Blueprint $table) {
            // Primary key
            $table->id();

            // The user who is a chat agent
            $table->foreignId('user_id')
                ->constrained()
                ->onDelete('cascade')
                ->comment('The user designated as chat agent');

            // Who appointed this agent
            $table->foreignId('appointed_by')
                ->constrained('users')
                ->onDelete('cascade')
                ->comment('Super Manager or Manager who appointed the agent');

            // Categories the agent can handle (optional, null = all categories)
            $table->json('categories')->nullable()->comment('JSON array of category IDs agent can handle');

            // Agent status
            $table->enum('status', ['online', 'away', 'offline', 'busy'])
                ->default('offline')
                ->comment('Current agent availability status');

            // Active status (can be deactivated without removing)
            $table->boolean('is_active')
                ->default(true)
                ->comment('Whether agent assignment is active');

            // Max concurrent chats
            $table->integer('max_concurrent_chats')->default(3)->comment('Maximum simultaneous conversations');

            // Current workload
            $table->integer('current_chats')->default(0)->comment('Current active conversations');

            // Statistics
            $table->integer('total_conversations')->default(0)->comment('Total conversations handled');
            $table->decimal('avg_response_time', 8, 2)->default(0)->comment('Average response time in minutes');
            $table->decimal('satisfaction_rating', 3, 2)->default(0)->comment('Average satisfaction rating (0-5)');

            // Availability schedule (JSON with days and hours)
            $table->json('availability_schedule')->nullable()->comment('Agent availability schedule');

            // Last activity
            $table->timestamp('last_active_at')->nullable()->comment('Last activity timestamp');

            // Standard timestamps
            $table->timestamps();
            $table->softDeletes();

            // Indexes for performance
            $table->index('user_id');
            $table->index('status');
            $table->index('is_active');
            $table->unique('user_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('chat_agents');
    }
};
