<?php

namespace Database\Seeders;

use App\Models\DocumentTemplate;
use App\Models\DocumentTemplateApprovalLine;
use App\Models\DocumentTemplateBasicField;
use App\Models\DocumentTemplateColumn;
use App\Models\DocumentTemplateSection;
use App\Models\DocumentTemplateSectionField;
use App\Models\DocumentTemplateSectionItem;
use Illuminate\Database\Seeder;

class IncomingInspectionTemplateSeeder extends Seeder
{
    private int $tenantId = 287;

    public function run(): void
    {
        $templates = $this->getTemplateDefinitions();

        foreach ($templates as $def) {
            $this->cleanupExisting($def['name']);

            $template = DocumentTemplate::create([
                'tenant_id' => $this->tenantId,
                'name' => $def['name'],
                'category' => '품질/수입검사',
                'title' => '수 입 검 사 성 적 서',
                'company_name' => '케이디산업',
                'footer_remark_label' => '부적합 내용',
                'footer_judgement_label' => '종합판정',
                'footer_judgement_options' => ['합격', '불합격'],
                'is_active' => true,
            ]);

            $this->createApprovalLines($template->id);
            $this->createBasicFields($template->id);
            $this->createSection($template->id, $def['section_title'], $def['items']);
            $this->createSectionFields($template->id);
            $this->createColumns($template->id);

            $this->command->info("✅ {$def['name']} (ID: {$template->id})");
        }
    }

    private function getTemplateDefinitions(): array
    {
        return [
            // ─── EGI (전기아연도금강판) ───
            [
                'name' => 'EGI 수입검사 성적서',
                'section_title' => '전기 아연도금 강판 (KS D 3528, SECC) "EGI 절곡판"',
                'items' => [
                    [
                        'category' => '겉모양',
                        'item' => '겉모양',
                        'standard' => '사용상 해로울 결함이 없을 것',
                        'method' => '육안검사',
                        'frequency' => 'n=3, c=0',
                        'regulation' => 'KS D 3528',
                    ],
                    [
                        'category' => '치수',
                        'item' => '두께',
                        'standard' => '0.8~1.0: ±0.07 / 1.0~1.25: ±0.08 / 1.25~1.6: ±0.10 / 1.6~2.0: ±0.12',
                        'method' => '체크검사',
                        'frequency' => 'n=3, c=0',
                        'regulation' => 'KS D 3528',
                    ],
                    [
                        'category' => '치수',
                        'item' => '너비',
                        'standard' => '1250 미만: +7/-0',
                        'method' => '체크검사',
                        'frequency' => 'n=3, c=0',
                        'regulation' => 'KS D 3528',
                    ],
                    [
                        'category' => '치수',
                        'item' => '길이',
                        'standard' => '~1250: +10/-0 / 2000~4000: +15/-0 / 4000~6000: +20/-0',
                        'method' => '체크검사',
                        'frequency' => 'n=3, c=0',
                        'regulation' => 'KS D 3528',
                    ],
                    [
                        'category' => '기계적성질',
                        'item' => '인장강도 (N/mm²)',
                        'standard' => '270 이상',
                        'method' => '공급업체 밀시트',
                        'frequency' => '입고시',
                        'regulation' => 'KS D 3528',
                    ],
                    [
                        'category' => '기계적성질',
                        'item' => '연신율 (%)',
                        'standard' => '0.6~1.0: 36이상 / 1.0~1.6: 37이상 / 1.6~2.3: 38이상',
                        'method' => '공급업체 밀시트',
                        'frequency' => '입고시',
                        'regulation' => 'KS D 3528',
                        'field_values' => ['reference_attribute' => 'thickness'],
                    ],
                    [
                        'category' => '도금',
                        'item' => '아연 최소 부착량 (g/m²)',
                        'standard' => '한면 17 이상',
                        'method' => '공급업체 밀시트',
                        'frequency' => '입고시',
                        'regulation' => 'KS F 4510',
                    ],
                ],
            ],

            // ─── SUS (스테인리스강판) ───
            [
                'name' => 'SUS 수입검사 성적서',
                'section_title' => '냉간 압연 스테인리스 강판 (KS D 3698, STS304) "SUS 절곡판"',
                'items' => [
                    [
                        'category' => '겉모양',
                        'item' => '겉모양',
                        'standard' => '사용상 해로울 결함이 없을 것',
                        'method' => '육안검사',
                        'frequency' => 'n=3, c=0',
                        'regulation' => 'KS D 3698',
                    ],
                    [
                        'category' => '치수',
                        'item' => '두께',
                        'standard' => '1.0~1.25: ±0.10 / 1.25~1.6: ±0.12',
                        'method' => '체크검사',
                        'frequency' => 'n=3, c=0',
                        'regulation' => 'KS D 3698',
                    ],
                    [
                        'category' => '치수',
                        'item' => '너비',
                        'standard' => '1250 미만: +7/-0',
                        'method' => '체크검사',
                        'frequency' => 'n=3, c=0',
                        'regulation' => 'KS D 3698',
                    ],
                    [
                        'category' => '치수',
                        'item' => '길이',
                        'standard' => '~3500: +10/-0 / 3500~6000: +20/-0',
                        'method' => '체크검사',
                        'frequency' => 'n=3, c=0',
                        'regulation' => 'KS D 3698',
                    ],
                    [
                        'category' => '기계적성질',
                        'item' => '항복강도 (N/mm²)',
                        'standard' => '205 이상',
                        'method' => '공급업체 밀시트',
                        'frequency' => '입고시',
                        'regulation' => 'KS D 3698',
                    ],
                    [
                        'category' => '기계적성질',
                        'item' => '인장강도 (N/mm²)',
                        'standard' => '520 이상',
                        'method' => '공급업체 밀시트',
                        'frequency' => '입고시',
                        'regulation' => 'KS D 3698',
                    ],
                    [
                        'category' => '기계적성질',
                        'item' => '연신율 (%)',
                        'standard' => '40 이상',
                        'method' => '공급업체 밀시트',
                        'frequency' => '입고시',
                        'regulation' => 'KS D 3698',
                    ],
                    [
                        'category' => '기계적성질',
                        'item' => '경도 (HV)',
                        'standard' => '200 이하',
                        'method' => '공급업체 밀시트',
                        'frequency' => '입고시',
                        'regulation' => 'KS D 3698',
                    ],
                ],
            ],
        ];
    }

    /**
     * 결재라인: 담당 / 부서장 (5130 동일)
     */
    private function createApprovalLines(int $templateId): void
    {
        $lines = [
            ['name' => '담당', 'dept' => '품질', 'role' => '담당자', 'sort_order' => 1],
            ['name' => '부서장', 'dept' => '품질', 'role' => '부서장', 'sort_order' => 2],
        ];

        foreach ($lines as $line) {
            DocumentTemplateApprovalLine::create(array_merge(
                ['template_id' => $templateId],
                $line,
            ));
        }
    }

    /**
     * 기본정보 필드 (5130 공통)
     */
    private function createBasicFields(int $templateId): void
    {
        $fields = [
            ['label' => '품명', 'field_type' => 'text', 'sort_order' => 1],
            ['label' => '규격 (두께*너비*길이)', 'field_type' => 'text', 'sort_order' => 2],
            ['label' => '납품업체', 'field_type' => 'text', 'sort_order' => 3],
            ['label' => '제조업체', 'field_type' => 'text', 'sort_order' => 4],
            ['label' => '로트번호', 'field_type' => 'text', 'sort_order' => 5],
            ['label' => '자재번호', 'field_type' => 'text', 'sort_order' => 6],
            ['label' => '검사일자', 'field_type' => 'date', 'sort_order' => 7],
            ['label' => '로트크기', 'field_type' => 'text', 'sort_order' => 8],
            ['label' => '단위', 'field_type' => 'text', 'sort_order' => 9],
            ['label' => '검사자', 'field_type' => 'text', 'sort_order' => 10],
        ];

        foreach ($fields as $field) {
            DocumentTemplateBasicField::create(array_merge(
                ['template_id' => $templateId],
                $field,
            ));
        }
    }

    /**
     * 검사 기준서 섹션 + 항목
     */
    private function createSection(int $templateId, string $title, array $items): void
    {
        $section = DocumentTemplateSection::create([
            'template_id' => $templateId,
            'title' => $title,
            'sort_order' => 1,
        ]);

        foreach ($items as $i => $item) {
            DocumentTemplateSectionItem::create(array_merge(
                ['section_id' => $section->id, 'sort_order' => $i + 1],
                $item,
            ));
        }
    }

    /**
     * 검사 기준서 동적 필드 정의 (수입검사 공통)
     */
    private function createSectionFields(int $templateId): void
    {
        $fields = [
            ['field_key' => 'category', 'label' => '분류', 'field_type' => 'text', 'width' => '80px', 'is_required' => false, 'sort_order' => 1],
            ['field_key' => 'item', 'label' => '검사항목', 'field_type' => 'text', 'width' => '120px', 'is_required' => true, 'sort_order' => 2],
            ['field_key' => 'standard', 'label' => '검사기준', 'field_type' => 'text', 'width' => '150px', 'is_required' => true, 'sort_order' => 3],
            ['field_key' => 'method', 'label' => '검사방식', 'field_type' => 'select', 'width' => '100px', 'is_required' => false, 'sort_order' => 4],
            ['field_key' => 'frequency', 'label' => '검사주기', 'field_type' => 'text', 'width' => '80px', 'is_required' => false, 'sort_order' => 5],
            ['field_key' => 'regulation', 'label' => '관련규격', 'field_type' => 'text', 'width' => '100px', 'is_required' => false, 'sort_order' => 6],
        ];

        foreach ($fields as $field) {
            DocumentTemplateSectionField::create(array_merge(
                ['template_id' => $templateId],
                $field,
            ));
        }
    }

    /**
     * 데이터 테이블 컬럼 (5130 공통 구조)
     */
    private function createColumns(int $templateId): void
    {
        $columns = [
            ['label' => 'NO', 'column_type' => 'text', 'width' => '50px', 'sort_order' => 1],
            ['label' => '검사항목', 'column_type' => 'text', 'width' => '120px', 'sort_order' => 2],
            ['label' => '검사기준', 'column_type' => 'text', 'width' => '150px', 'sort_order' => 3],
            ['label' => '검사방식', 'column_type' => 'text', 'width' => '100px', 'sort_order' => 4],
            ['label' => '검사주기', 'column_type' => 'text', 'width' => '100px', 'sort_order' => 5],
            [
                'label' => '측정치',
                'column_type' => 'complex',
                'group_name' => '측정치',
                'sub_labels' => ['n1', 'n2', 'n3'],
                'width' => '240px',
                'sort_order' => 6,
            ],
            ['label' => '판정 (적/부)', 'column_type' => 'select', 'width' => '80px', 'sort_order' => 7],
        ];

        foreach ($columns as $col) {
            DocumentTemplateColumn::create(array_merge(
                ['template_id' => $templateId],
                $col,
            ));
        }
    }

    private function cleanupExisting(string $name): void
    {
        $existing = DocumentTemplate::where('tenant_id', $this->tenantId)
            ->where('name', $name)
            ->first();

        if (! $existing) {
            return;
        }

        DocumentTemplateColumn::where('template_id', $existing->id)->delete();
        DocumentTemplateSectionField::where('template_id', $existing->id)->delete();
        $sections = DocumentTemplateSection::where('template_id', $existing->id)->get();
        foreach ($sections as $section) {
            DocumentTemplateSectionItem::where('section_id', $section->id)->delete();
        }
        DocumentTemplateSection::where('template_id', $existing->id)->delete();
        DocumentTemplateBasicField::where('template_id', $existing->id)->delete();
        DocumentTemplateApprovalLine::where('template_id', $existing->id)->delete();
        $existing->forceDelete();
    }
}
