<?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::create('support_tickets', function (Blueprint $table) {
            $table->id();
            $table->foreignId('organization_id')->constrained()->cascadeOnDelete();
            $table->foreignId('created_by')->constrained('users')->cascadeOnDelete();
            $table->string('subject');
            // open → in_progress (admin replied) → closed
            $table->enum('status', ['open', 'in_progress', 'closed'])->default('open');
            $table->timestamp('last_message_at')->useCurrent();
            $table->timestamps();

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

        Schema::create('support_messages', function (Blueprint $table) {
            $table->id();
            $table->foreignId('ticket_id')->constrained('support_tickets')->cascadeOnDelete();
            $table->foreignId('sender_id')->constrained('users')->cascadeOnDelete();
            // true = sent by platform admin; false = sent by org user
            $table->boolean('is_platform_reply')->default(false);
            $table->text('body');
            // Nullable timestamps indicating when each side read this message.
            // null = unread for that side.
            $table->timestamp('read_by_org_at')->nullable();
            $table->timestamp('read_by_admin_at')->nullable();
            $table->timestamps();

            $table->index('ticket_id');
        });
    }

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