<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('messages', function (Blueprint $table) {
            if (!Schema::hasColumn('messages', 'twilio_sid')) {
                $table->string('twilio_sid')->nullable()->index();
            }
            if (!Schema::hasColumn('messages', 'direction')) {
                $table->string('direction');
            }
            if (!Schema::hasColumn('messages', 'channel')) {
                $table->string('channel')->default('whatsapp');
            }
            if (!Schema::hasColumn('messages', 'to_number')) {
                $table->string('to_number')->nullable();
            }
            if (!Schema::hasColumn('messages', 'status')) {
                $table->string('status')->default('queued');
            }
            if (!Schema::hasColumn('messages', 'payload')) {
                $table->json('payload')->nullable();
            }
            if (!Schema::hasColumn('messages', 'student_id')) {
                $table->foreignId('student_id')->nullable()->constrained('students');
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('messages', function (Blueprint $table) {
            if (Schema::hasColumn('messages', 'student_id')) { $table->dropConstrainedForeignId('student_id'); }
            if (Schema::hasColumn('messages', 'payload')) { $table->dropColumn('payload'); }
            if (Schema::hasColumn('messages', 'status')) { $table->dropColumn('status'); }
            if (Schema::hasColumn('messages', 'to_number')) { $table->dropColumn('to_number'); }
            if (Schema::hasColumn('messages', 'channel')) { $table->dropColumn('channel'); }
            if (Schema::hasColumn('messages', 'direction')) { $table->dropColumn('direction'); }
            if (Schema::hasColumn('messages', 'twilio_sid')) { $table->dropIndex(['twilio_sid']); $table->dropColumn('twilio_sid'); }
        });
    }
};
