<?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_conversations table for managing chat sessions.
     * 
     * Requirements: 4.1, 4.4, 8.3
     */
    public function up(): void
    {
        Schema::create('chat_conversations', function (Blueprint $table) {
            // Primary key
            $table->id();

            // Unique identifier for visitor tracking (stored in cookie)
            $table->string('session_id', 191)->unique()->comment('Unique session identifier');

            // Category assignment
            $table->foreignId('category_id')
                ->nullable()
                ->constrained('chat_categories')
                ->nullOnDelete()
                ->comment('Selected chat category');

            // Agent assignment
            $table->foreignId('agent_id')
                ->nullable()
                ->constrained('users')
                ->nullOnDelete()
                ->comment('Assigned chat agent');

            // Visitor information
            $table->string('visitor_name', 191)->nullable()->comment('Visitor provided name');
            $table->string('visitor_email', 191)->nullable()->comment('Visitor provided email');
            $table->string('visitor_phone', 50)->nullable()->comment('Visitor provided phone');
            $table->string('visitor_ip', 45)->nullable()->comment('Visitor IP address (IPv6 compatible)');

            // Visitor metadata
            $table->text('user_agent')->nullable()->comment('Browser user agent');
            $table->json('metadata')->nullable()->comment('Additional visitor data (browser, OS, etc.)');

            // Custom data collected from visitor
            $table->json('custom_fields')->nullable()->comment('Custom form fields collected from visitor');

            // Initial question/message
            $table->text('initial_message')->nullable()->comment('First message from visitor');

            // Conversation status
            $table->enum('status', ['waiting', 'active', 'resolved', 'missed', 'closed'])
                ->default('waiting')
                ->comment('Conversation status');

            // Priority level
            $table->enum('priority', ['low', 'normal', 'high'])->default('normal');

            // Timestamps for conversation lifecycle
            $table->timestamp('started_at')->nullable()->comment('When conversation started');
            $table->timestamp('first_response_at')->nullable()->comment('When agent first responded');
            $table->timestamp('ended_at')->nullable()->comment('When conversation ended');
            $table->timestamp('last_message_at')->nullable()->comment('Timestamp of last message');

            // Duration tracking (in seconds)
            $table->integer('wait_time')->default(0)->comment('Wait time before first response (seconds)');
            $table->integer('duration')->default(0)->comment('Total conversation duration (seconds)');

            // Resolution tracking
            $table->text('resolution_notes')->nullable()->comment('Notes about how issue was resolved');

            // Who ended the conversation
            $table->foreignId('ended_by')
                ->nullable()
                ->constrained('users')
                ->nullOnDelete()
                ->comment('Agent who ended the conversation');

            // End reason
            $table->string('end_reason', 191)->nullable()->comment('Reason for ending conversation');

            // Visitor satisfaction rating (1-5)
            $table->tinyInteger('satisfaction_rating')->nullable()->comment('Visitor rating 1-5');
            $table->text('satisfaction_comment')->nullable()->comment('Visitor feedback');

            // Message counts
            $table->integer('message_count')->default(0);
            $table->integer('visitor_message_count')->default(0);
            $table->integer('agent_message_count')->default(0);

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

            // Indexes for performance
            $table->index('status');
            $table->index('agent_id');
            $table->index('category_id');
            $table->index('started_at');
            $table->index('last_message_at');
            $table->index('satisfaction_rating');
            $table->index(['agent_id', 'status']);
            $table->index(['category_id', 'status']);
        });
    }

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