<?php

namespace App\Observers;

use App\Models\Folder;
use App\Models\Tenants\Tenant;
use App\Services\TenantBootstrapper;
use Illuminate\Support\Facades\Log;

class TenantObserver
{
    public function created(Tenant $tenant): void
    {
        // 테넌트 부트스트랩 실행
        app(TenantBootstrapper::class)->bootstrap((int) $tenant->id, 'STANDARD');

        // 기본 폴더 생성
        try {
            $defaultFolders = [
                [
                    'folder_key' => 'product',
                    'folder_name' => '생산관리',
                    'description' => '생산 관련 문서 및 도면',
                    'icon' => 'icon-production',
                    'color' => '#3B82F6',
                    'display_order' => 1,
                ],
                [
                    'folder_key' => 'quality',
                    'folder_name' => '품질관리',
                    'description' => '품질 검사 및 인증 문서',
                    'icon' => 'icon-quality',
                    'color' => '#10B981',
                    'display_order' => 2,
                ],
                [
                    'folder_key' => 'accounting',
                    'folder_name' => '회계',
                    'description' => '회계 관련 증빙 서류',
                    'icon' => 'icon-accounting',
                    'color' => '#F59E0B',
                    'display_order' => 3,
                ],
                [
                    'folder_key' => 'hr',
                    'folder_name' => '인사',
                    'description' => '인사 관련 문서',
                    'icon' => 'icon-hr',
                    'color' => '#8B5CF6',
                    'display_order' => 4,
                ],
                [
                    'folder_key' => 'general',
                    'folder_name' => '일반',
                    'description' => '기타 문서',
                    'icon' => 'icon-general',
                    'color' => '#6B7280',
                    'display_order' => 5,
                ],
            ];

            foreach ($defaultFolders as $folder) {
                Folder::create([
                    'tenant_id' => $tenant->id,
                    'folder_key' => $folder['folder_key'],
                    'folder_name' => $folder['folder_name'],
                    'description' => $folder['description'],
                    'icon' => $folder['icon'],
                    'color' => $folder['color'],
                    'display_order' => $folder['display_order'],
                    'is_active' => true,
                ]);
            }

            Log::info('Created default folders for new tenant', ['tenant_id' => $tenant->id]);
        } catch (\Exception $e) {
            Log::error('Failed to create default folders for tenant', [
                'tenant_id' => $tenant->id,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
