<?php
// database/migrations/2025_09_05_043744_create_job_events_table.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
    {
        // If already created (e.g., in another deploy), do nothing.
        if (Schema::hasTable('job_events')) {
            return;
        }

        Schema::create('job_events', function (Blueprint $table) {
            $table->id();

            // Parent job
            $table->foreignId('job_id')
                ->constrained('jobs')
                ->cascadeOnDelete();

            // Event type (kept short to stay within MySQL index byte limits)
            // Examples: "hold.created", "email.sent"
            $table->string('type', 100)->index();

            // Arbitrary event data
            $table->json('payload')->nullable();

            // When the event actually happened (vs created_at)
            $table->timestamp('occurred_at')->nullable()->index();

            $table->timestamps();

            // Helpful composite index for common queries:
            // WHERE job_id = ? AND type = ?
            $table->index(['job_id', 'type'], 'job_events_job_id_type_index');
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('job_events')) {
            return;
        }

        Schema::dropIfExists('job_events');
    }
};
