<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Controllers\Api;

use App\Core\App;
use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Modules\SportsActivity\Services\SlotAvailabilityService;
use App\Modules\SportsActivity\Services\ConflictDetectionService;

class ScheduleApiController extends Controller
{
    public function availability(Request $request): Response
    {
        $unitId = (int) $request->get('unit_id', 0);
        $date = $request->get('date', '');
        $startTime = $request->get('start_time', '');
        $endTime = $request->get('end_time', '');
        $spots = (int) $request->get('spots', 1);

        if (!$unitId || !$date || !$startTime || !$endTime) {
            return $this->json(['error' => 'معاملات ناقصة'], 400);
        }

        $result = SlotAvailabilityService::check($unitId, $date, $startTime, $endTime, $spots);
        return $this->json($result);
    }

    public function conflicts(Request $request): Response
    {
        $unitId = (int) $request->get('unit_id', 0);
        $date = $request->get('date', '');
        $startTime = $request->get('start_time', '');
        $endTime = $request->get('end_time', '');
        $coachId = $request->get('coach_id') ? (int) $request->get('coach_id') : null;

        if (!$unitId || !$date || !$startTime || !$endTime) {
            return $this->json(['error' => 'معاملات ناقصة'], 400);
        }

        $conflicts = ConflictDetectionService::check($unitId, $date, $startTime, $endTime, $coachId);
        return $this->json(['conflicts' => $conflicts, 'has_blocking' => !empty(array_filter($conflicts, fn($c) => $c['severity'] === 'blocking'))]);
    }
}
