<?php

namespace App\Services\SchoolYears;

use App\Models\Configuration;
use App\Models\SchoolYear;

class SchoolYearResolver
{
    public function ensureCurrentTracked(): ?SchoolYear
    {
        $current = trim((string) (Configuration::getConfig('school_year') ?? ''));
        if ($current === '') {
            return SchoolYear::query()->where('is_current', true)->orderByDesc('id')->first();
        }

        $existing = SchoolYear::query()->where('name', $current)->first();
        if ($existing) {
            if ($existing->status !== SchoolYear::STATUS_ACTIVE || !$existing->is_current) {
                SchoolYear::query()->where('id', '!=', $existing->id)->where('is_current', true)->update([
                    'is_current' => false,
                    'updated_at' => now(),
                ]);
                $existing->status = SchoolYear::STATUS_ACTIVE;
                $existing->is_current = true;
                $existing->save();
            }

            return $existing->refresh();
        }

        [$startDate, $endDate] = $this->inferDatesFromName($current);
        SchoolYear::query()->where('is_current', true)->update([
            'is_current' => false,
            'updated_at' => now(),
        ]);

        return SchoolYear::query()->create([
            'name' => $current,
            'start_date' => $startDate,
            'end_date' => $endDate,
            'status' => SchoolYear::STATUS_ACTIVE,
            'is_current' => true,
        ]);
    }

    public function inferDatesFromName(string $schoolYear): array
    {
        if (preg_match('/^(\\d{4})-(\\d{4})$/', trim($schoolYear), $matches) === 1) {
            return [
                sprintf('%s-09-01', $matches[1]),
                sprintf('%s-06-30', $matches[2]),
            ];
        }

        $year = (int) date('Y');

        return [
            sprintf('%d-09-01', $year),
            sprintf('%d-06-30', $year + 1),
        ];
    }

    public function suggestNextName(string $schoolYear): ?string
    {
        if (preg_match('/^(\\d{4})-(\\d{4})$/', trim($schoolYear), $matches) !== 1) {
            return null;
        }

        return sprintf('%d-%d', (int) $matches[1] + 1, (int) $matches[2] + 1);
    }
}
