<?php

namespace Database\Seeders;

use App\Models\Intake;
use App\Models\Programme;
use Illuminate\Database\Seeder;
use Illuminate\Support\Carbon;

/**
 * Intakes and their open programmes (PRD 29).
 *
 * The August intake is the one kcu.ac.ug currently advertises as OPEN.
 */
class IntakeSeeder extends Seeder
{
    public function run(): void
    {
        $year = (int) now()->year;

        $intakes = [
            [
                'name' => "August Intake {$year}",
                'year' => $year,
                'application_open_at' => Carbon::create($year, 4, 1, 0, 0, 0),
                'application_close_at' => Carbon::create($year, 9, 30, 23, 59, 59),
                'start_date' => Carbon::create($year, 10, 12),
                'status' => 'open',
                'is_default' => true,
                'description' => 'Applications are open for the August intake across all schools.',
            ],
            [
                'name' => 'January Intake '.($year + 1),
                'year' => $year + 1,
                'application_open_at' => Carbon::create($year, 10, 1, 0, 0, 0),
                'application_close_at' => Carbon::create($year + 1, 1, 31, 23, 59, 59),
                'start_date' => Carbon::create($year + 1, 2, 8),
                'status' => 'upcoming',
                'is_default' => false,
                'description' => 'The January intake opens for applications in October.',
            ],
        ];

        $programmeIds = Programme::query()->pluck('id');

        foreach ($intakes as $data) {
            $intake = Intake::updateOrCreate(
                ['slug' => str($data['name'])->slug()->value()],
                $data,
            );

            // Every active programme accepts applications in both intakes,
            // inheriting the intake's own window unless overridden in admin.
            $intake->intakeProgrammes()->delete();

            foreach ($programmeIds as $programmeId) {
                $intake->intakeProgrammes()->create([
                    'programme_id' => $programmeId,
                    'status' => 'active',
                ]);
            }
        }

        $this->command?->info(sprintf(
            'Seeded %d intakes covering %d programmes each.',
            count($intakes),
            $programmeIds->count(),
        ));
    }
}
