from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from datetime import datetime
from typing import List, Optional
from modules.auth.dependencies import get_current_user
from core.database import get_db
from modules.auth.models import User
from modules.calendar.schemas import (
    CalendarEventCreate,
    CalendarEventUpdate,
    CalendarEventResponse,
)
from modules.calendar.service import (
    create_calendar_event,
    get_calendar_event_by_id,
    get_calendar_events,
    update_calendar_event,
    delete_calendar_event,
)

router = APIRouter(prefix="/calendar", tags=["calendar"])


@router.post(
    "/events", response_model=CalendarEventResponse, status_code=status.HTTP_201_CREATED
)
def create_event(
    event: CalendarEventCreate,
    user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
):
    return create_calendar_event(db, user.id, event)


@router.get("/events", response_model=List[CalendarEventResponse])
def get_events(
    user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
    start: Optional[datetime] = None,
    end: Optional[datetime] = None,
):
    return get_calendar_events(db, user.id, start, end)


@router.get("/events/{event_id}", response_model=CalendarEventResponse)
def get_event_by_id(
    event_id: int, user: User = Depends(get_current_user), db: Session = Depends(get_db)
):
    event = get_calendar_event_by_id(db, user.id, event_id)
    return event


@router.patch("/events/{event_id}", response_model=CalendarEventResponse)
def update_event(
    event_id: int,
    event: CalendarEventUpdate,
    user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
):
    return update_calendar_event(db, user.id, event_id, event)


@router.delete("/events/{event_id}", status_code=204)
def delete_event(
    event_id: int, user: User = Depends(get_current_user), db: Session = Depends(get_db)
):
    delete_calendar_event(db, user.id, event_id)
