<?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
    {
        // sales_partners 테이블에 유치 파트너 컬럼 추가
        Schema::table('sales_partners', function (Blueprint $table) {
            $table->unsignedBigInteger('referrer_partner_id')->nullable()->after('notes')
                ->comment('이 단체를 유치한 영업파트너 ID');
            $table->foreign('referrer_partner_id')->references('id')->on('sales_partners')->nullOnDelete();
        });

        // sales_commissions 테이블에 유치수당 관련 컬럼 추가
        Schema::table('sales_commissions', function (Blueprint $table) {
            $table->unsignedBigInteger('referrer_partner_id')->nullable()->after('manager_user_id')
                ->comment('유치수당 받을 파트너 ID');
            $table->decimal('referrer_rate', 5, 2)->default(0)->after('referrer_partner_id')
                ->comment('유치 수당률 (%)');
            $table->decimal('referrer_commission', 14, 2)->default(0)->after('referrer_rate')
                ->comment('유치 수당액');
            $table->date('first_referrer_paid_at')->nullable()->after('referrer_commission')
                ->comment('1차 유치수당 지급일');
            $table->date('second_referrer_paid_at')->nullable()->after('first_referrer_paid_at')
                ->comment('2차 유치수당 지급일');

            $table->foreign('referrer_partner_id')->references('id')->on('sales_partners')->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('sales_commissions', function (Blueprint $table) {
            $table->dropForeign(['referrer_partner_id']);
            $table->dropColumn([
                'referrer_partner_id',
                'referrer_rate',
                'referrer_commission',
                'first_referrer_paid_at',
                'second_referrer_paid_at',
            ]);
        });

        Schema::table('sales_partners', function (Blueprint $table) {
            $table->dropForeign(['referrer_partner_id']);
            $table->dropColumn('referrer_partner_id');
        });
    }
};
