<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateDisputesTableWithSla extends Migration
{
    public function up()
    {
        if (Schema::hasTable('disputes')) {
            return;
        }

        Schema::create('disputes', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('order_id');
            $table->unsignedBigInteger('initiator_id'); // Qui a ouvert (buyer ou seller)
            $table->unsignedBigInteger('respondent_id'); // L'autre partie
            $table->unsignedBigInteger('assigned_to')->nullable(); // Verifier assigné
            
            $table->enum('status', ['open', 'in_review', 'resolved', 'escalated', 'cancelled'])->default('open')->index();
            $table->enum('type', ['quality', 'non_delivery', 'payment_issue', 'fraud', 'other'])->index();
            $table->text('description');
            $table->text('resolution')->nullable();
            
            // SLA Management
            $table->timestamp('opened_at');
            $table->timestamp('deadline_at'); // Défaut +7 jours
            $table->timestamp('resolved_at')->nullable();
            $table->boolean('sla_breached')->default(false);
            $table->timestamp('escalation_triggered_at')->nullable();
            
            // Résolution
            $table->enum('decision', ['in_favor_of_buyer', 'in_favor_of_seller', 'partial_refund'])->nullable();
            $table->decimal('refund_amount', 15, 2)->nullable();
            
            // Audit
            $table->unsignedBigInteger('resolved_by')->nullable(); // Verifier qui a résolu
            $table->text('notes')->nullable();
            
            $table->timestamps();
            $table->softDeletes();
            
            $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
            $table->foreign('initiator_id')->references('id')->on('users')->onDelete('restrict');
            $table->foreign('respondent_id')->references('id')->on('users')->onDelete('restrict');
            $table->foreign('assigned_to')->references('id')->on('users')->onDelete('set null');
            $table->foreign('resolved_by')->references('id')->on('users')->onDelete('set null');
            
            $table->index('deadline_at');
            $table->index(['status', 'sla_breached']);
        });
    }

    public function down()
    {
        Schema::dropIfExists('disputes');
    }
}
