<?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_deductions', function (Blueprint $table) {
            $table->id();
            $table->string('deduction_number')->unique();
            $table->foreignId('merchant_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('invoice_id')->nullable()->constrained('merchant_invoices')->onDelete('set null');
            $table->enum('deduction_type', ['penalty', 'return_charge', 'damage_claim', 'late_payment_fee', 'service_charge', 'other'])->default('other');
            $table->decimal('amount', 12, 2);
            $table->date('deduction_date');
            $table->text('reason');
            $table->text('notes')->nullable();
            $table->enum('status', ['pending', 'approved', 'rejected', 'applied'])->default('pending');
            $table->foreignId('approved_by')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamp('approved_at')->nullable();
            $table->timestamps();

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

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