<?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('purchase_requests', function (Blueprint $table) {
            // Add missing workflow fields
            $table->foreignId('submitted_by')->nullable()->constrained('users')->nullOnDelete()->after('rejection_reason');
            $table->timestamp('submitted_at')->nullable()->after('submitted_by');
            $table->foreignId('reviewed_by')->nullable()->constrained('users')->nullOnDelete()->after('submitted_at');
            $table->timestamp('reviewed_at')->nullable()->after('reviewed_by');

            // Add indexes for better performance (guard fields)
            if (Schema::hasColumn('purchase_requests', 'priority')) {
                $table->index(['status', 'priority']);
            }
            if (Schema::hasColumn('purchase_requests', 'required_date')) {
                $table->index(['status', 'required_date']);
            }
            if (Schema::hasColumn('purchase_requests', 'submitted_at')) {
                $table->index(['submitted_at']);
            }
            if (Schema::hasColumn('purchase_requests', 'approved_at')) {
                $table->index(['approved_at']);
            }
        });
    }

    public function down(): void
    {
        Schema::table('purchase_requests', function (Blueprint $table) {
            // Drop indexes
            $table->dropIndex(['status', 'priority']);
            $table->dropIndex(['status', 'required_date']);
            $table->dropIndex(['submitted_at']);
            $table->dropIndex(['approved_at']);

            // Drop foreign keys
            $table->dropConstrainedForeignId('submitted_by');
            $table->dropConstrainedForeignId('reviewed_by');

            // Drop columns
            $table->dropColumn(['submitted_at', 'reviewed_at']);
        });
    }
};
