<?php

declare(strict_types=1);

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('support_tickets', function (Blueprint $table): void {
            $table->string('ticket_reference')->nullable()->unique()->after('id');
            $table->string('customer_email')->nullable()->index()->after('user_id');
        });

        // Make user_id nullable to support tickets created via email from unknown senders
        Schema::table('support_tickets', function (Blueprint $table): void {
            $table->unsignedBigInteger('user_id')->nullable()->change();
        });

        Schema::table('ticket_replies', function (Blueprint $table): void {
            $table->string('message_id')->nullable()->index()->after('is_staff_reply');
            $table->string('from_email')->nullable()->after('message_id');
            $table->boolean('via_email')->default(false)->after('from_email');
        });

        // Make user_id nullable to support replies from unknown email senders
        Schema::table('ticket_replies', function (Blueprint $table): void {
            $table->unsignedBigInteger('user_id')->nullable()->change();
        });
    }

    public function down(): void
    {
        Schema::table('support_tickets', function (Blueprint $table): void {
            $table->dropColumn(['ticket_reference', 'customer_email']);
        });

        Schema::table('support_tickets', function (Blueprint $table): void {
            $table->unsignedBigInteger('user_id')->nullable(false)->change();
        });

        Schema::table('ticket_replies', function (Blueprint $table): void {
            $table->dropColumn(['message_id', 'from_email', 'via_email']);
        });

        Schema::table('ticket_replies', function (Blueprint $table): void {
            $table->unsignedBigInteger('user_id')->nullable(false)->change();
        });
    }
};
