<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('crm_settings', function (Blueprint $table) {
            // WhatsApp Business Account + webhook wiring.
            $table->string('business_account_id')->nullable()->after('phone_number_id');
            $table->string('verify_token')->nullable()->after('access_token'); // webhook handshake
            // Business-initiated messages need an approved template outside the
            // 24-hour customer-care window. When on, the rendered body is sent
            // as the single {{1}} body parameter of this template.
            $table->boolean('use_templates')->default(false)->after('verify_token');
            $table->string('template_name')->nullable()->after('use_templates');
            $table->string('template_lang')->default('fa')->after('template_name');
            $table->timestamp('verified_at')->nullable()->after('template_lang'); // last good connection test
        });

        Schema::table('crm_messages', function (Blueprint $table) {
            $table->string('wa_message_id')->nullable()->after('channel'); // Meta's wamid, maps status callbacks
            $table->timestamp('delivered_at')->nullable()->after('sent_at');
            $table->timestamp('read_at')->nullable()->after('delivered_at');
            $table->index('wa_message_id');
        });
    }

    public function down(): void
    {
        Schema::table('crm_messages', function (Blueprint $table) {
            $table->dropColumn(['wa_message_id', 'delivered_at', 'read_at']);
        });
        Schema::table('crm_settings', function (Blueprint $table) {
            $table->dropColumn(['business_account_id', 'verify_token', 'use_templates', 'template_name', 'template_lang', 'verified_at']);
        });
    }
};
