""" Event-Service relationship endpoints """
from typing import List
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session
from datetime import datetime
from sqlalchemy import select

from app.api.deps import (
    CurrentUser,
    SessionDep,
    get_current_active_superuser,
)
from app import crud
from app.models import EventServiceOut, EventServicesOut, Event, EventAllServicesOut, EventServiceUpdate, Service, EventsAllServicesOut, EventServiceCreate, EventData

router = APIRouter()

@router.post("/events/services", response_model=EventServiceOut)
def add_service_to_event(
    *,
    eventService: EventServiceCreate,
    session: SessionDep,
    current_user: CurrentUser
) -> EventServiceOut:
    """
    Add a service to an event.
    """
    # Verify that the event belongs to the current user
    event = session.get(Event, eventService.event_id)
    if not event or event.account_id != current_user.id:
        raise HTTPException(status_code=404, detail="Event not found")
    
    return crud.event_service.create_event_service(
        session=session,
        event_id=eventService.event_id,
        service_id=eventService.service_id,
        cantidad=eventService.cantidad,
        data_inicio=eventService.data_inicio,
        data_fin=eventService.data_fin
    )

@router.put("/events/{event_id}/services/{service_id}", response_model=EventServiceOut)
def update_service_in_event(
    *,
    event_id: UUID,
    service_id: UUID,
    obj_in: EventServiceUpdate,
    session: SessionDep,
    current_user: CurrentUser
) -> EventServiceOut:
    """
    Update a service quantity in an event.
    If cantidad is 0, the service will be removed from the event.
    """
    # Verify that the event belongs to the current user
    event = session.get(Event, event_id)
    if not event or event.account_id != current_user.id:
        raise HTTPException(status_code=404, detail="Event not found")
    
    result = crud.event_service.update_event_service(
        session=session,
        event_id=event_id,
        service_id=service_id,
        obj_in=obj_in
    )
    
    if result is None:
        raise HTTPException(status_code=200, detail="Service removed from event")
    
    return result

@router.delete("/events/{event_id}/services/{service_id}")
def remove_service_from_event(
    *,
    event_id: UUID,
    service_id: UUID,
    session: SessionDep,
    current_user: CurrentUser
) -> None:
    """
    Remove a service from an event.
    """
    # Verify that the event belongs to the current user
    event = session.get(Event, event_id)
    if not event or event.account_id != current_user.id:
        raise HTTPException(status_code=404, detail="Event not found")
    
    crud.event_service.delete_event_service(
        session=session,
        event_id=event_id,
        service_id=service_id
    )
    return {"message": "Service removed from event"}

@router.get("/events/{event_id}/services", response_model=EventServicesOut)
def get_event_services(
    *,
    event_id: UUID,
    skip: int = 0,
    limit: int = 100,
    session: SessionDep,
    current_user: CurrentUser
) -> EventServicesOut:
    """
    Get all services for an event.
    """
    # Verify that the event belongs to the current user
    event = session.get(Event, event_id)
    if not event:
        raise HTTPException(status_code=404, detail="Event not found")
    
    return crud.event_service.get_event_services(
        session=session,
        event_id=event_id,
        skip=skip,
        limit=limit
    )

@router.get("/events/{event_id}/all-services", response_model=EventAllServicesOut)
def get_all_services_for_event(
    *,
    event_id: UUID,
    session: SessionDep,
    current_user: CurrentUser
) -> EventAllServicesOut:
    """
    Get all services for an event with event details.
    """
    # Verify that the event belongs to the current user
    event = session.get(Event, event_id)
    if not event:
        raise HTTPException(status_code=404, detail="Event not found")
    
    return crud.event_service.get_all_services_for_event(
        session=session,
        event_id=event_id
    ) 

@router.get("/services/{service_id}/events", response_model=EventsAllServicesOut)
def get_events_for_service(
    *,
    service_id: UUID,
    session: SessionDep,
    current_user: CurrentUser
) -> List[EventAllServicesOut]:
    """
    Get all events where the service is included.
    Returns the list of events with their details.
    """
    # Verificar que el servicio existe (esto no verifica propiedad, solo existencia)
    service = session.get(Service, service_id)
    if not service:
        raise HTTPException(status_code=404, detail="Service not found")
    
    # Si el usuario actual es el propietario del servicio o un superusuario
    # puede ver todos los eventos donde se usa

    
    events = crud.event_service.get_events_for_service(
        session=session,
        service_id=service_id
    ) 
    return EventsAllServicesOut(data=events, count=len(events))

@router.get("/events/{event_id}/services/{service_id}", response_model=EventServiceOut)
def get_event_service_by_id(
    *,
    event_id: UUID,
    service_id: UUID,
    session: SessionDep,
    current_user: CurrentUser
) -> EventServiceOut:
    """
    Get a specific service for an event.
    """
    # Verify that the event belongs to the current user
    event = session.get(Event, event_id)
    if not event:
        raise HTTPException(status_code=404, detail="Event not found")
    
    return crud.event_service.get_event_service(
        session=session,
        event_id=event_id,
        service_id=service_id
    )



@router.post("/service-availability/{service_id}")
def check_service_availability(service_id: UUID, eventData: EventData, session: SessionDep):
    """
    Endpoint que devuelve si un servicio está disponible en el rango de fechas dado.
    """
    service = session.get(Service, service_id)
    if not service:
        raise HTTPException(status_code=404, detail="Service not found")
    cantidad, data_inicio, data_fin, price = crud.event_service.get_service_availability_for_event(
        session=session,
        service=service,
        eventData=eventData
    )
    return {"cantidad": cantidad, "data_inicio": data_inicio, "data_fin": data_fin, "price": price}