<?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('whatsapp_conversations', function (Blueprint $table) {
            $table->boolean('human_takeover')->default(false)->after('data');
            $table->timestamp('human_takeover_at')->nullable()->after('human_takeover');
            $table->foreignId('human_takeover_by')->nullable()->after('human_takeover_at')->constrained('users')->nullOnDelete();
            $table->timestamp('last_message_at')->nullable()->after('human_takeover_by');
        });

        Schema::create('whatsapp_messages', function (Blueprint $table) {
            $table->id();
            $table->string('phone', 20)->index();
            $table->string('sender_type', 16);
            $table->string('message_type', 32)->default('text');
            $table->text('body')->nullable();
            $table->json('meta')->nullable();
            $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();

            $table->index(['phone', 'id']);
        });
    }

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

        Schema::table('whatsapp_conversations', function (Blueprint $table) {
            $table->dropForeign(['human_takeover_by']);
            $table->dropColumn(['human_takeover', 'human_takeover_at', 'human_takeover_by', 'last_message_at']);
        });
    }
};
