<?php

namespace App\Services;

use App\Models\ExternalBusyWindow;
use Carbon\Carbon;

class BusyWindowService
{
    public static function getBusyRanges()
    {
        // Fetch current + upcoming busy windows
        return ExternalBusyWindow::where('ends_at', '>=', now())
            ->get()
            ->map(fn($w) => [
                'start' => Carbon::parse($w->starts_at)->subMinutes(40),
                'end'   => Carbon::parse($w->ends_at)->addMinutes(40),
            ]);
    }

	public static function isInBusyWindow($slotStart, $busyRanges, $slotLengthMinutes = 60)
	{
		$slotEnd = (clone $slotStart)->addMinutes($slotLengthMinutes);

		foreach ($busyRanges as $range) {
			// If the slot overlaps the busy window in any way
			if ($slotStart < $range['end'] && $slotEnd > $range['start']) {
				return true;
			}
		}
		return false;
	}
}