<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * price_histories 데이터를 prices 테이블로 이관
     */
    public function up(): void
    {
        // 기존 price_histories 데이터를 prices로 이관
        DB::statement("
            INSERT INTO prices (
                tenant_id,
                item_type_code,
                item_id,
                client_group_id,
                purchase_price,
                sales_price,
                effective_from,
                effective_to,
                status,
                created_by,
                updated_by,
                deleted_by,
                created_at,
                updated_at,
                deleted_at
            )
            SELECT
                tenant_id,
                item_type_code,
                item_id,
                client_group_id,
                CASE WHEN price_type_code = 'PURCHASE' THEN price ELSE NULL END as purchase_price,
                CASE WHEN price_type_code = 'SALE' THEN price ELSE NULL END as sales_price,
                started_at as effective_from,
                ended_at as effective_to,
                'active' as status,
                created_by,
                updated_by,
                deleted_by,
                created_at,
                updated_at,
                deleted_at
            FROM price_histories
            WHERE deleted_at IS NULL
        ");
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // prices 테이블에서 이관된 데이터 삭제
        // (원본 price_histories는 아직 존재하므로 prices만 비움)
        DB::table('prices')->truncate();
    }
};
