<?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::create('merchant_disputes', function (Blueprint $table) {
            $table->id();
            $table->string('dispute_number')->unique();
            $table->foreignId('merchant_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('invoice_id')->nullable()->constrained('merchant_invoices')->onDelete('set null');
            $table->foreignId('payment_id')->nullable()->constrained('merchant_payments')->onDelete('set null');
            $table->foreignId('deduction_id')->nullable()->constrained('merchant_deductions')->onDelete('set null');
            $table->enum('dispute_type', ['invoice_amount', 'payment_delay', 'deduction_query', 'service_issue', 'billing_error', 'other'])->default('other');
            $table->string('subject');
            $table->text('description');
            $table->decimal('disputed_amount', 12, 2)->nullable();
            $table->enum('priority', ['low', 'medium', 'high', 'urgent'])->default('medium');
            $table->enum('status', ['open', 'in_review', 'resolved', 'closed', 'escalated'])->default('open');
            $table->text('resolution')->nullable();
            $table->foreignId('assigned_to')->nullable()->constrained('users')->onDelete('set null');
            $table->foreignId('resolved_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamp('resolved_at')->nullable();
            $table->timestamps();

            $table->index(['merchant_id', 'status']);
            $table->index(['status', 'priority']);
            $table->index(['assigned_to']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('merchant_disputes');
    }
};
