<?php

namespace App\Services\ClassSections;

use App\Models\Configuration;
use App\Models\SchoolClass;
use Illuminate\Support\Facades\DB;

class ClassSectionSeedService
{
    public function seedDefaults(): int
    {
        $semester = (string) (Configuration::getConfig('semester') ?? '');
        $schoolYear = (string) (Configuration::getConfig('school_year') ?? '');

        $classes = [
            ['class_name' => 'Class 1', 'schedule' => 'Monday 9:00 AM - 10:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 2', 'schedule' => 'Tuesday 9:00 AM - 10:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 3', 'schedule' => 'Wednesday 9:00 AM - 10:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 4', 'schedule' => 'Thursday 9:00 AM - 10:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 5', 'schedule' => 'Friday 9:00 AM - 10:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 6', 'schedule' => 'Monday 10:00 AM - 11:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 7', 'schedule' => 'Tuesday 10:00 AM - 11:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 8', 'schedule' => 'Wednesday 10:00 AM - 11:00 AM', 'capacity' => 30],
            ['class_name' => 'Class 9', 'schedule' => 'Thursday 10:00 AM - 11:00 AM', 'capacity' => 30],
            ['class_name' => 'Youth', 'schedule' => 'Friday 10:00 AM - 11:00 AM', 'capacity' => 30],
        ];

        return DB::transaction(function () use ($classes, $semester, $schoolYear) {
            $created = 0;
            foreach ($classes as $class) {
                $row = SchoolClass::query()->firstOrCreate(
                    [
                        'class_name' => $class['class_name'],
                        'semester' => $semester,
                        'school_year' => $schoolYear,
                    ],
                    [
                        'schedule' => $class['schedule'],
                        'capacity' => $class['capacity'],
                    ]
                );

                if ($row->wasRecentlyCreated) {
                    $created++;
                }
            }

            return $created;
        });
    }
}
