<?php

namespace App\Services\Meet;

use App\Models\Room;
use Illuminate\Support\Carbon;

class AvailabilityService
{
    /**
     * @return array{available: bool, conflicts: array<int, array<string, mixed>>}
     */
    public function checkHostAvailability(
        string $hostUserRef,
        int $organizationId,
        Carbon $start,
        int $durationMinutes,
        ?int $excludeRoomId = null,
    ): array {
        $end = (clone $start)->addMinutes($durationMinutes);

        $conflicts = Room::query()
            ->where('organization_id', $organizationId)
            ->where('host_user_ref', $hostUserRef)
            ->whereIn('status', ['scheduled', 'live'])
            ->when($excludeRoomId, fn ($q) => $q->where('id', '!=', $excludeRoomId))
            ->whereNotNull('scheduled_at')
            ->get()
            ->filter(function (Room $room) use ($start, $end) {
                $roomStart = Carbon::parse($room->scheduled_at);
                $roomEnd = (clone $roomStart)->addMinutes($room->duration_minutes ?? 60);

                return $start->lt($roomEnd) && $end->gt($roomStart);
            })
            ->map(fn (Room $room) => [
                'uuid' => $room->uuid,
                'title' => $room->title,
                'scheduled_at' => $room->scheduled_at?->toIso8601String(),
                'duration_minutes' => $room->duration_minutes,
            ])
            ->values()
            ->all();

        return [
            'available' => count($conflicts) === 0,
            'conflicts' => $conflicts,
        ];
    }
}
