<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('business_income_payments', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id')->nullable()->change();
            $table->string('display_name', 100)->nullable()->after('user_id')->comment('상호/성명 (표시용)');
            $table->string('business_reg_number', 20)->nullable()->after('display_name')->comment('사업자등록번호');
        });

        // 기존 데이터에 display_name/business_reg_number 채우기
        DB::statement("
            UPDATE business_income_payments bip
            JOIN tenant_user_profiles tup ON tup.user_id = bip.user_id
                AND tup.tenant_id = bip.tenant_id AND tup.worker_type = 'business_income'
            SET bip.display_name = COALESCE(
                JSON_UNQUOTE(JSON_EXTRACT(tup.json_extra, '$.business_name')),
                (SELECT name FROM users WHERE id = bip.user_id)
            ),
            bip.business_reg_number = JSON_UNQUOTE(JSON_EXTRACT(tup.json_extra, '$.business_registration_number'))
            WHERE bip.display_name IS NULL
        ");

        // earner 프로필 없는 경우 users 테이블에서 이름만이라도 채우기
        DB::statement("
            UPDATE business_income_payments bip
            JOIN users u ON u.id = bip.user_id
            SET bip.display_name = u.name
            WHERE bip.display_name IS NULL AND bip.user_id IS NOT NULL
        ");
    }

    public function down(): void
    {
        Schema::table('business_income_payments', function (Blueprint $table) {
            $table->dropColumn(['display_name', 'business_reg_number']);
            $table->unsignedBigInteger('user_id')->nullable(false)->change();
        });
    }
};
