<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\CalendarService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CalendarController extends Controller
{
    public function __construct(private readonly CalendarService $calendarService) {}

    public function events(Request $request): JsonResponse
    {
        $data = $request->validate([
            'from' => 'nullable|date',
            'to' => 'nullable|date|after_or_equal:from',
            'types' => 'nullable|array',
            'types.*' => 'string|in:meeting,task,sprint,project,action_item',
        ]);

        $from = Carbon::parse($data['from'] ?? now()->startOfMonth())->startOfDay();
        $to = Carbon::parse($data['to'] ?? now()->endOfMonth())->endOfDay();

        if ($from->diffInDays($to) > 93) {
            return response()->json(['success' => false, 'message' => 'بازه تقویم نمی‌تواند بیشتر از ۹۳ روز باشد.'], 422);
        }

        return response()->json([
            'success' => true,
            'data' => $this->calendarService->events($request->user(), $from, $to, $data['types'] ?? []),
            'meta' => ['from' => $from->toDateString(), 'to' => $to->toDateString()],
            'message' => 'رویدادهای تقویم',
        ]);
    }
}
