<?php

namespace Database\Seeders;

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

class ProjectCharterRiskSeeder 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 risks for {$charters->count()} project charters...");

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

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

            // Create 2-5 risks per charter
            $riskCount = fake()->numberBetween(2, 5);

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

            // Ensure at least one high-risk item per charter
            if ($riskCount >= 3) {
                ProjectCharterRisk::factory()
                    ->for($charter)
                    ->highRisk()
                    ->create([
                        'org_id' => $charter->org_id,
                        'created_by' => $orgUsers->random()->id,
                    ]);
            }
        }

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

        // Display some statistics
        $highRisks = ProjectCharterRisk::where('incident_likelihood', 'high')
            ->orWhere('impact_level', 'high')
            ->count();

        $this->command->info("High-risk items: {$highRisks}");
    }
}
