<?php

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

/**
 * wa_templates — reusable message templates. For Meta channels these mirror the
 * approved WABA templates (template name + language + components). For free-text
 * (web) channels the body is rendered directly with {{var}} substitution.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('wa_templates')) {
            return;
        }

        Schema::create('wa_templates', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id')->index();
            $table->string('name', 120)->comment('Internal key, e.g. invoice_created');
            $table->string('language', 12)->default('en');
            $table->string('category', 40)->default('utility')->comment('utility|marketing|authentication');

            // Meta-approved template linkage
            $table->string('meta_template_name', 160)->nullable();
            $table->enum('meta_status', ['none', 'pending', 'approved', 'rejected'])->default('none');

            $table->text('header')->nullable();
            $table->text('body')->comment('Supports {{var}} placeholders');
            $table->text('footer')->nullable();
            $table->json('buttons')->nullable();
            $table->json('variables')->nullable()->comment('Ordered variable names for {{1}}.. mapping');

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

            $table->unique(['business_id', 'name']);
        });
    }

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