<?php

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

/**
 * wa_auto_replies — the chat workflow engine. Rules evaluated on every inbound
 * message BEFORE the AI: a greeting on the first message, keyword FAQ replies,
 * and a catch-all fallback. A matching rule can optionally stop the pipeline
 * (so the AI doesn't also answer).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('wa_auto_replies')) {
            return;
        }

        Schema::create('wa_auto_replies', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id')->index();
            $table->string('name', 120);
            $table->enum('trigger', ['welcome', 'keyword', 'fallback'])->default('keyword');
            $table->string('keyword', 191)->nullable()->comment('Comma-separated keywords for trigger=keyword');
            $table->enum('match', ['contains', 'exact', 'starts'])->default('contains');

            $table->unsignedInteger('template_id')->nullable();
            $table->text('body')->nullable()->comment('Used when no template is set');
            $table->boolean('stop_after')->default(true)->comment('Stop the pipeline (skip AI) when this rule fires');

            $table->unsignedInteger('priority')->default(10);
            $table->boolean('active')->default(true);
            $table->timestamps();

            $table->index(['business_id', 'active', 'priority']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('wa_auto_replies');
    }
};
