<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

/**
 * 견적 수식 품목 매핑 시더
 *
 * 완제품별 BOM 품목과 수량/단가 수식 정의
 *
 * FG-SCR-001 (방화스크린 소형) BOM:
 *   - SF-SCR-F01 (스크린 원단): W*H/1000000 M2
 *   - SF-SCR-F02 (가이드레일 좌): H/1000 M
 *   - SF-SCR-F03 (가이드레일 우): H/1000 M
 *   - SF-SCR-F04 (케이스): 1 EA
 *   - SF-SCR-F05 (하부프레임): 1 EA
 *   - SF-SCR-M01 (모터): 1 EA
 *   - SF-SCR-C01 (제어반): 1 EA
 *   - SF-SCR-S01 (셋팅박스): 1 SET
 *   - SF-SCR-W01 (권선드럼): 1 EA
 *   - SF-SCR-B01 (브라켓): 1 SET
 *   - SF-SCR-SW01 (스위치): 1 EA
 *   - SM-B002 (볼트): 1 EA
 *   - SM-N002 (너트): 1 EA
 *   - SM-W002 (와셔): 1 EA
 */
class QuoteFormulaItemSeeder extends Seeder
{
    public function run(): void
    {
        $tenantId = 1;

        // 품목매핑 카테고리 ID 조회
        $categoryId = DB::table('quote_formula_categories')
            ->where('tenant_id', $tenantId)
            ->where('code', 'item_mapping')
            ->value('id');

        if (! $categoryId) {
            $this->command->error('QuoteFormulaItemSeeder: 품목매핑 카테고리가 없습니다. QuoteFormulaCategorySeeder를 먼저 실행하세요.');

            return;
        }

        // 완제품 조회
        $products = DB::table('items')
            ->where('tenant_id', $tenantId)
            ->where('item_type', 'FG')
            ->whereIn('code', ['FG-SCR-001', 'FG-STL-001'])
            ->pluck('id', 'code')
            ->toArray();

        if (empty($products)) {
            $this->command->warn('QuoteFormulaItemSeeder: 완제품이 없습니다. DesignItemSeeder를 먼저 실행하세요.');

            return;
        }

        $formulaItems = [];

        // === FG-SCR-001 (방화스크린 소형) BOM ===
        if (isset($products['FG-SCR-001'])) {
            // 매핑 수식 생성
            $formulaId = DB::table('quote_formulas')->insertGetId([
                'tenant_id' => $tenantId,
                'category_id' => $categoryId,
                'product_id' => $products['FG-SCR-001'],
                'name' => 'FG-SCR-001 BOM 매핑',
                'variable' => 'BOM_SCR_001',
                'type' => 'mapping',
                'formula' => null,
                'output_type' => 'item',
                'description' => '방화스크린 소형 BOM 품목 매핑',
                'sort_order' => 100,
                'is_active' => true,
                'created_by' => 1,
                'updated_by' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            $screenItems = [
                ['code' => 'SF-SCR-F01', 'name' => '스크린 원단', 'spec' => 'A급 방화원단', 'unit' => 'M2', 'qty_formula' => 'W*H/1000000', 'price_formula' => null],
                ['code' => 'SF-SCR-F02', 'name' => '가이드레일 (좌)', 'spec' => '알루미늄 프로파일', 'unit' => 'M', 'qty_formula' => 'H/1000', 'price_formula' => null],
                ['code' => 'SF-SCR-F03', 'name' => '가이드레일 (우)', 'spec' => '알루미늄 프로파일', 'unit' => 'M', 'qty_formula' => 'H/1000', 'price_formula' => null],
                ['code' => 'SF-SCR-F04', 'name' => '케이스', 'spec' => '스틸 도장', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SF-SCR-F05', 'name' => '하부프레임', 'spec' => '스틸 도장', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SF-SCR-M01', 'name' => '모터 (소형)', 'spec' => '350W 220V', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SF-SCR-C01', 'name' => '제어반', 'spec' => '단독형', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SF-SCR-S01', 'name' => '셋팅박스', 'spec' => '표준형', 'unit' => 'SET', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SF-SCR-W01', 'name' => '권선드럼', 'spec' => '표준형', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SF-SCR-B01', 'name' => '브라켓 세트', 'spec' => '벽면형', 'unit' => 'SET', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SF-SCR-SW01', 'name' => '스위치', 'spec' => '3단 스위치', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SM-B002', 'name' => '볼트 M8x25', 'spec' => 'SUS304', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SM-N002', 'name' => '너트 M8', 'spec' => 'SUS304', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SM-W002', 'name' => '와셔 M8', 'spec' => 'SUS304', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
            ];

            foreach ($screenItems as $i => $item) {
                $formulaItems[] = [
                    'formula_id' => $formulaId,
                    'item_code' => $item['code'],
                    'item_name' => $item['name'],
                    'specification' => $item['spec'],
                    'unit' => $item['unit'],
                    'quantity_formula' => $item['qty_formula'],
                    'unit_price_formula' => $item['price_formula'],
                    'sort_order' => $i + 1,
                ];
            }
        }

        // === FG-STL-001 (철재도어 소형) BOM ===
        if (isset($products['FG-STL-001'])) {
            // 매핑 수식 생성
            $formulaId = DB::table('quote_formulas')->insertGetId([
                'tenant_id' => $tenantId,
                'category_id' => $categoryId,
                'product_id' => $products['FG-STL-001'],
                'name' => 'FG-STL-001 BOM 매핑',
                'variable' => 'BOM_STL_001',
                'type' => 'mapping',
                'formula' => null,
                'output_type' => 'item',
                'description' => '철재도어 소형 BOM 품목 매핑',
                'sort_order' => 200,
                'is_active' => true,
                'created_by' => 1,
                'updated_by' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            $steelItems = [
                ['code' => 'SF-STL-P01', 'name' => '도어 패널', 'spec' => '1.2T 강판', 'unit' => 'M2', 'qty_formula' => 'W*H/1000000', 'price_formula' => null],
                ['code' => 'SF-STL-F01', 'name' => '문틀 프레임', 'spec' => '1.6T 강판', 'unit' => 'M', 'qty_formula' => '(W+H)*2/1000', 'price_formula' => null],
                ['code' => 'SF-STL-G01', 'name' => '유리창', 'spec' => '방화유리', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SF-STL-H01', 'name' => '힌지', 'spec' => '스틸 힌지', 'unit' => 'SET', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SF-STL-L01', 'name' => '잠금장치', 'spec' => '레버형', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SF-STL-C01', 'name' => '도어클로저', 'spec' => '유압식', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SF-STL-S01', 'name' => '실링재', 'spec' => '방화 패킹', 'unit' => 'M', 'qty_formula' => '(W+H)*2/1000', 'price_formula' => null],
                ['code' => 'SF-STL-PT01', 'name' => '파우더 도장', 'spec' => '방청도장', 'unit' => 'M2', 'qty_formula' => 'W*H/1000000*2', 'price_formula' => null],
                ['code' => 'SM-B002', 'name' => '볼트 M8x25', 'spec' => 'SUS304', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
                ['code' => 'SM-N002', 'name' => '너트 M8', 'spec' => 'SUS304', 'unit' => 'EA', 'qty_formula' => '1', 'price_formula' => null],
            ];

            foreach ($steelItems as $i => $item) {
                $formulaItems[] = [
                    'formula_id' => $formulaId,
                    'item_code' => $item['code'],
                    'item_name' => $item['name'],
                    'specification' => $item['spec'],
                    'unit' => $item['unit'],
                    'quantity_formula' => $item['qty_formula'],
                    'unit_price_formula' => $item['price_formula'],
                    'sort_order' => $i + 1,
                ];
            }
        }

        // 데이터 삽입
        foreach ($formulaItems as $item) {
            DB::table('quote_formula_items')->insert(array_merge($item, [
                'created_at' => now(),
                'updated_at' => now(),
            ]));
        }

        $this->command->info('QuoteFormulaItemSeeder: '.count($formulaItems).'개 품목 매핑 생성 완료');
        $this->command->info('  - FG-SCR-001: '.(isset($products['FG-SCR-001']) ? '14개 품목' : '미생성'));
        $this->command->info('  - FG-STL-001: '.(isset($products['FG-STL-001']) ? '10개 품목' : '미생성'));
    }
}
