<?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::create('partner_withdrawals', function (Blueprint $table) {
            $table->id();
            $table->foreignId('company_id')->constrained()->cascadeOnDelete();
            $table->foreignId('partner_id')->constrained()->cascadeOnDelete();

            // Financial
            $table->decimal('amount', 15, 2);
            $table->enum('type', [
                'profit_withdrawal',   // Retiro de utilidades
                'capital_return',      // Devolucion de capital
                'dividend_payment',    // Pago de dividendos
            ]);
            $table->string('method')->nullable();

            // Tracking
            $table->date('operation_date');
            $table->string('reference')->nullable();
            $table->text('notes')->nullable();
            $table->json('metadata')->nullable();

            // Link to Expense record for accounting integrity
            $table->foreignId('expense_id')->nullable()->constrained()->nullOnDelete();

            // Approval
            $table->enum('approval_status', ['pending', 'approved', 'rejected'])->default('pending');
            $table->foreignId('approved_by_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('approved_at')->nullable();
            $table->text('approval_notes')->nullable();

            // Audit
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->boolean('is_locked')->default(false);
            $table->timestamp('locked_at')->nullable();

            $table->timestamps();

            // Indexes
            $table->index(['company_id', 'partner_id']);
            $table->index(['company_id', 'operation_date']);
            $table->index(['company_id', 'approval_status']);
            $table->index('expense_id');
        });
    }

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