<?php

namespace Database\Seeders;

use App\Models\SprintBacklog;
use App\Models\Requirement;
use App\Models\NonFunctionalRequirement;
use App\Models\Sprint;
use Illuminate\Database\Seeder;

class SprintBacklogSeeder extends Seeder
{
    public function run(): void
    {
        SprintBacklog::truncate();

        $requirements = Requirement::all();
        $sprints = Sprint::pluck('id', 'name');
        $nfrsByProject = NonFunctionalRequirement::all()->groupBy('project_id');

        // Requirements distribution per sprint
        $sprintRequirements = [
            'Sprint 1' => 2,
            'Sprint 2' => 1,
            'Sprint 3' => 2,
        ];

        $requirementCounter = 0;
        $rows = [];
        $now = now();

        foreach ($sprintRequirements as $sprintName => $reqCount) {
            if (!isset($sprints[$sprintName])) {
                continue;
            }

            for ($i = 0; $i < $reqCount && $requirementCounter < $requirements->count(); $i++) {
                $requirement = $requirements[$requirementCounter];
                $projectNfrs = $nfrsByProject[$requirement->project_id] ?? collect();

                // ✅ Ensure exactly 5 NFRs are attached
                foreach ($projectNfrs->take(5) as $nfr) {
                    $rows[] = [
                        'r_id'       => $requirement->id,
                        'nfu_id'     => $nfr->id,
                        'project_id' => $requirement->project_id,
                        'sprint_id'  => $sprints[$sprintName],
                        'status'     => 'pending',
                        'created_at' => $now,
                        'updated_at' => $now,
                    ];
                }

                $requirementCounter++;
            }
        }

        if (!empty($rows)) {
            SprintBacklog::insert($rows);
        }

        $this->command->info("✅ Sprint backlogs seeded successfully. Each requirement has 5 NFRs.");
    }
}
