<?php

namespace App\Services;

use App\Models\ClassSession;
use App\Models\ScheduleSetting;
use Carbon\Carbon;
use Illuminate\Support\Collection;

class ScheduleService
{
    /** @var array<int, string> */
    private const DAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];

    public function weekStart(): Carbon
    {
        $setting = ScheduleSetting::query()->first();

        return $setting?->week_start_date
            ? Carbon::parse($setting->week_start_date)->startOfDay()
            : Carbon::now()->startOfWeek(Carbon::MONDAY);
    }

    /** @return array<string, Carbon> */
    public function weekDates(): array
    {
        $start = $this->weekStart();
        $dates = [];

        foreach (self::DAYS as $index => $day) {
            $dates[$day] = $start->copy()->addDays($index);
        }

        return $dates;
    }

    /** @return Collection<string, Collection<int, ClassSession>> */
    public function sessionsByDay(): Collection
    {
        $sessions = ClassSession::query()
            ->with(['classType', 'coach'])
            ->where('is_active', true)
            ->orderBy('start_time')
            ->get();

        return collect(self::DAYS)->mapWithKeys(function (string $day) use ($sessions) {
            return [
                $day => $sessions->where('day_of_week', $day)->values(),
            ];
        });
    }

    /** @return Collection<int, ClassSession> */
    public function filterableSessions(): Collection
    {
        return ClassSession::query()
            ->with(['classType', 'coach'])
            ->where('is_active', true)
            ->get();
    }
}
