<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Project;
use App\Models\Sprint;
use App\Models\ProjectSprint;

class ProjectSprintSeeder extends Seeder
{
    public function run(): void
    {
        $assignments = [
            'E-Commerce Website' => ['Sprint 1', 'Sprint 2', 'Sprint 3'],
            'Mobile Banking App' => ['Sprint 1', 'Sprint 2'],
        ];

        $projectsByName = Project::all()->keyBy('name');
        $sprintsByName  = Sprint::all()->keyBy('name');

        foreach ($assignments as $projectName => $sprintNames) {
            $project = $projectsByName[$projectName] ?? null;
            if (!$project) {
                continue;
            }

            // Build pivot data for attach
            $pivotData = collect($sprintNames)
                ->mapWithKeys(function ($sprintName) use ($sprintsByName) {
                    $sprint = $sprintsByName[$sprintName] ?? null;
                    return $sprint
                        ? [$sprint->id => ['status' => ProjectSprint::STATUS_PENDING]]
                        : [];
                })
                ->toArray();

            // Attach while ignoring duplicates
            $project->sprints()->syncWithoutDetaching($pivotData);
        }

        $this->command->info('✅ Project sprints seeded successfully (all pending).');
    }
}
