<?php

namespace Database\Seeders;

use App\Models\ProjectCharter;
use App\Models\ProjectCharterFile;
use Illuminate\Database\Seeder;

class ProjectCharterFileSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Get all existing project charters
        $charters = ProjectCharter::all();

        if ($charters->isEmpty()) {
            $this->command->info('No project charters found. Please seed project charters first.');

            return;
        }

        $this->command->info("Seeding files for {$charters->count()} project charters...");

        foreach ($charters as $charter) {
            // Get users from the same organization for file creation
            $org = $charter->org;
            $orgUsers = $org ? $org->users()->get() : collect();

            if ($orgUsers->isEmpty()) {
                // Fall back to charter creator
                $orgUsers = collect([$charter->createdBy]);
            }

            // Create 3-8 files per charter
            $fileCount = fake()->numberBetween(3, 8);

            for ($i = 0; $i < $fileCount; $i++) {
                ProjectCharterFile::factory()->create([
                    'project_charter_id' => $charter->id,
                    'org_id' => $charter->org_id,
                    'created_by' => $orgUsers->random()->id,
                ]);
            }

            // Ensure each charter has at least one main planning document
            ProjectCharterFile::factory()->create([
                'project_charter_id' => $charter->id,
                'org_id' => $charter->org_id,
                'created_by' => $orgUsers->random()->id,
                'name' => 'وثيقة ميثاق المشروع الرسمية',
                'description' => 'الوثيقة الرسمية المعتمدة لميثاق المشروع تحتوي على جميع التفاصيل والموافقات',
            ]);

            // Add budget spreadsheet for each charter
            ProjectCharterFile::factory()->create([
                'project_charter_id' => $charter->id,
                'org_id' => $charter->org_id,
                'created_by' => $orgUsers->random()->id,
                'name' => 'ميزانية المشروع التفصيلية',
                'description' => 'جدول تفصيلي لميزانية المشروع وتوزيع التكاليف',
            ]);
        }

        $totalFiles = ProjectCharterFile::count();
        $this->command->info("تم إنشاء {$totalFiles} ملف ميثاق المشروع بنجاح!");
    }
}
