<?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::table('price_histories', function (Blueprint $table) {
            $table->unsignedBigInteger('client_group_id')
                ->nullable()
                ->after('price_type_code')
                ->comment('고객 그룹 ID (NULL = 기본 가격, 값 있으면 그룹별 차등 가격)');

            // 기존 인덱스에 client_group_id 추가
            $table->dropIndex('idx_price_histories_main');
            $table->index(['tenant_id', 'item_type_code', 'item_id', 'client_group_id', 'started_at'], 'idx_price_histories_main');

            $table->foreign('client_group_id')->references('id')->on('client_groups')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('price_histories', function (Blueprint $table) {
            $table->dropForeign(['client_group_id']);
            $table->dropIndex('idx_price_histories_main');
            $table->index(['tenant_id', 'item_type_code', 'item_id', 'started_at'], 'idx_price_histories_main');
            $table->dropColumn('client_group_id');
        });
    }
};
