<?php

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

/**
 * Phase 0: 데이터 정규화
 *
 * products 테이블에서 비표준 item_type 삭제
 * - 표준: FG(완제품), PT(부품)
 * - 비표준(삭제): PRODUCT, SUBASSEMBLY, PART, CS
 *
 * 개발 중이므로 비표준 데이터 삭제 처리
 * 품목관리 완료 후 경동기업 데이터 전체 재세팅 예정
 */
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 1. 삭제 전 건수 확인
        $beforeCount = DB::table('products')->count();
        $nonStandardCount = DB::table('products')
            ->whereNotIn('product_type', ['FG', 'PT'])
            ->count();

        Log::info('Phase 0: Normalizing item_types', [
            'total_before' => $beforeCount,
            'non_standard_count' => $nonStandardCount,
        ]);

        // 2. 비표준 products와 관련된 product_components 삭제
        $bomDeleted = DB::table('product_components')
            ->whereIn('parent_product_id', function ($query) {
                $query->select('id')
                    ->from('products')
                    ->whereNotIn('product_type', ['FG', 'PT']);
            })
            ->orWhere(function ($query) {
                $query->where('ref_type', 'PRODUCT')
                    ->whereIn('ref_id', function ($q) {
                        $q->select('id')
                            ->from('products')
                            ->whereNotIn('product_type', ['FG', 'PT']);
                    });
            })
            ->delete();

        // 3. 비표준 products 삭제 (Soft Delete 아닌 Hard Delete)
        $deleted = DB::table('products')
            ->whereNotIn('product_type', ['FG', 'PT'])
            ->delete();

        // 4. 삭제 후 건수 확인
        $afterCount = DB::table('products')->count();

        Log::info('Phase 0: Normalization complete', [
            'bom_deleted' => $bomDeleted,
            'products_deleted' => $deleted,
            'total_after' => $afterCount,
        ]);
    }

    /**
     * Reverse the migrations.
     *
     * 삭제된 데이터는 복구 불가 (개발 중이므로 허용)
     */
    public function down(): void
    {
        Log::warning('Phase 0 rollback: Deleted data cannot be restored');
    }
};
