<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('chatbots', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->string('sender'); // Device sender
            $table->string('name');
            $table->text('description')->nullable();
            $table->string('type')->default('rule-based'); // rule-based, ai, hybrid
            $table->boolean('is_active')->default(true);
            $table->json('config')->nullable(); // chatbot configuration
            $table->json('intents')->nullable(); // predefined intents and responses
            $table->string('fallback_message')->nullable();
            $table->integer('priority')->default(0);
            $table->timestamps();
            
            $table->index(['user_id', 'sender']);
            $table->index('is_active');
        });
        
        Schema::create('chatbot_sessions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('chatbot_id')->constrained()->onDelete('cascade');
            $table->string('phone'); // Customer phone
            $table->string('session_id');
            $table->json('context')->nullable(); // Session context/variables
            $table->string('current_state')->nullable();
            $table->timestamp('last_activity')->nullable();
            $table->timestamps();
            
            $table->index(['chatbot_id', 'phone']);
            $table->index('session_id');
        });
        
        Schema::create('chatbot_conversations', function (Blueprint $table) {
            $table->id();
            $table->foreignId('chatbot_session_id')->constrained()->onDelete('cascade');
            $table->text('user_message')->nullable();
            $table->text('bot_response')->nullable();
            $table->string('intent')->nullable();
            $table->decimal('confidence', 5, 2)->nullable();
            $table->timestamps();
        });
    }

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