<?php

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

/**
 * wa_channels — one configured WhatsApp number per business location.
 * A channel is served by one driver: 'meta' (official Cloud API) or 'web'
 * (WhatsApp-Web through a Node bridge paired by QR scan).
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('wa_channels')) {
            return;
        }

        Schema::create('wa_channels', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id')->index();
            $table->unsignedInteger('location_id')->nullable()->index()
                  ->comment('business_locations.id — lets every location use its own number');
            $table->string('label', 120);
            $table->enum('driver', ['meta', 'web'])->default('meta');
            $table->string('display_number', 30)->nullable()->comment('E.164 number shown to staff');

            $table->enum('status', ['connecting', 'scanning', 'active', 'disconnected', 'disabled'])
                  ->default('connecting');
            $table->boolean('is_default')->default(false)
                  ->comment('Default channel for automated messages when none specified');

            // Meta Cloud API credentials
            $table->string('meta_phone_number_id', 60)->nullable();
            $table->string('meta_waba_id', 60)->nullable();
            $table->text('meta_access_token')->nullable();
            $table->string('meta_verify_token', 80)->nullable();

            // WhatsApp-Web (Node bridge) fields
            $table->string('api_token', 80)->nullable()->unique()
                  ->comment('Bearer token the Node bridge authenticates with');
            $table->text('qr_code')->nullable()->comment('Latest QR payload awaiting scan (transient)');
            $table->string('connected_as', 40)->nullable()->comment('Linked phone wa_id once paired');
            $table->json('session_meta')->nullable();
            $table->string('bridge_version', 20)->nullable();

            $table->timestamp('last_heartbeat_at')->nullable();
            $table->timestamp('last_connected_at')->nullable();
            $table->timestamp('disconnected_at')->nullable();
            $table->ipAddress('last_ip')->nullable();
            $table->boolean('rescan_alert_sent')->default(false)
                  ->comment('Guards against repeat disconnect alerts');

            $table->json('meta')->nullable();
            $table->timestamps();

            $table->index(['business_id', 'status']);
            $table->index(['business_id', 'location_id']);
        });
    }

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