<?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\DocumentTemplateSectionItem;
use Illuminate\Database\Seeder;

class InspectionTemplateSeeder extends Seeder
{
    /**
     * 수입검사 성적서 템플릿 - 검사항목 테이블만
     */
    public function run(): void
    {
        $tenantId = 1;
        $this->cleanupExisting($tenantId);

        // 템플릿 생성
        $template = DocumentTemplate::create([
            'tenant_id' => $tenantId,
            'name' => '철제품 수입검사 성적서',
            'category' => '품질/수입검사',
            'title' => '수입검사 성적서',
            'is_active' => true,
        ]);

        // 검사항목 섹션
        $section = DocumentTemplateSection::create([
            'template_id' => $template->id,
            'title' => '검사 항목',
            'sort_order' => 1,
        ]);

        // 검사항목 (React 모달과 동일)
        $items = [
            ['item' => '겉모양', 'standard' => '외관 이상 없음', 'method' => '육안'],
            ['item' => '두께', 'standard' => 't 1.0', 'method' => '계측'],
            ['item' => '폭', 'standard' => 'W 1,000mm', 'method' => '계측'],
            ['item' => '길이', 'standard' => 'L 2,000mm', 'method' => '계측'],
        ];

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

        $this->command->info("✅ 템플릿 생성 완료 (ID: {$template->id})");
    }

    private function cleanupExisting(int $tenantId): void
    {
        $existing = DocumentTemplate::where('tenant_id', $tenantId)
            ->where('name', '철제품 수입검사 성적서')
            ->first();

        if ($existing) {
            DocumentTemplateColumn::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();
        }
    }
}
