<?php

declare(strict_types=1);

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('owner_payouts', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('owner_id')->constrained('owners')->cascadeOnDelete();
            $table->bigInteger('amount_cents');
            $table->string('currency_code', 3)->default('NZD');
            $table->string('payout_method')->default('bank_transfer');
            $table->string('reference')->nullable();
            $table->timestamp('paid_at')->nullable();
            $table->timestamps();
        });

        // simple link: each ledger entry can reference payout_id
        Schema::table('owner_ledger_entries', function (Blueprint $table): void {
            if (! Schema::hasColumn('owner_ledger_entries', 'payout_id')) {
                $table->foreignId('payout_id')
                    ->nullable()
                    ->after('job_id')
                    ->constrained('owner_payouts')
                    ->nullOnDelete();
            }
        });
    }

    public function down(): void
    {
        Schema::table('owner_ledger_entries', function (Blueprint $table): void {
            if (Schema::hasColumn('owner_ledger_entries', 'payout_id')) {
                $table->dropConstrainedForeignId('payout_id');
            }
        });

        Schema::dropIfExists('owner_payouts');
    }
};
