<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Requirement;
use App\Models\RequirementOperation;
use App\Models\NonFunctionalRequirement;
use Illuminate\Database\Seeder;

class RequirementOperationSeeder extends Seeder
{
    public function run(): void
    {
        // Clear existing data before seeding
        RequirementOperation::truncate();

        $users = User::all();
        $requirements = Requirement::all();
        $nfrsByProject = NonFunctionalRequirement::all()->groupBy('project_id');

        // Define the allowed nfu_values
        $allowedValues = [0.001, 0.25, 0.5, 0.75, 1];
        
        $rows = [];
        $now = now();

        foreach ($users as $user) {
            foreach ($requirements as $requirement) {
                $projectNfrs = $nfrsByProject[$requirement->project_id] ?? collect();

                // ✅ Ensure exactly 5 NFRs per requirement-operation
                foreach ($projectNfrs->take(5) as $nfr) {
                    // Randomly select one value from the allowed values array
                    $randomValue = $allowedValues[array_rand($allowedValues)];
                    
                    $rows[] = [
                        'user_id'    => $user->id,
                        'r_id'       => $requirement->id,
                        'nfu_id'     => $nfr->id,
                        'project_id' => $requirement->project_id,
                        'nfu_value'  => $randomValue,
                        'status'     => 'done', // Changed from 'pending' to 'done'
                        'created_at' => $now,
                        'updated_at' => $now,
                    ];
                }
            }
        }

        // Bulk insert for performance
        if (!empty($rows)) {
            RequirementOperation::insert($rows);
        }

        $this->command->info("✅ Requirement operations seeded successfully. Each requirement-operation has 5 NFRs with random nfu_values from [0.001, 0.25, 0.5, 0.75, 1] and status set to 'done'.");
    }
}