from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import SessionLocal
from models.event_model import Event
from schemas.event_schema import EventCreate
from models.user_model import User

router = APIRouter()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def authenticate_user(email: str, db: Session):
    user = db.query(User).filter(User.email == email).first()
    if not user:
        raise HTTPException(status_code=401, detail="Unauthorized: Invalid email")
    return user

@router.post("/event/create")
def create_event(
    event: EventCreate,
    email: str = Query(..., description="User email for authentication"),
    db: Session = Depends(get_db)
):
    authenticate_user(email, db)
    new_event = Event(
        event_name=event.event_name,
        purpose=event.purpose,
        date=event.date,
        start_time=event.start_time,
        end_time=event.end_time
    )
    db.add(new_event)
    db.commit()
    db.refresh(new_event)
    return {"message": "Event created successfully", "event": {
        "id": new_event.id,
        "event_name": new_event.event_name,
        "purpose": new_event.purpose,
        "date": new_event.date,
        "start_time": new_event.start_time,
        "end_time": new_event.end_time
    }}

@router.get("/event/list")
def list_events(
    email: str = Query(..., description="User email for authentication"),
    db: Session = Depends(get_db)
):
    authenticate_user(email, db)
    events = db.query(Event).all()
    return [
        {
            "id": event.id,
            "event_name": event.event_name,
            "purpose": event.purpose,
            "date": event.date,
            "start_time": event.start_time,
            "end_time": event.end_time
        }
        for event in events
    ]
@router.delete("/event/delete/{event_id}")
def delete_event(
    event_id: int,
    email: str = Query(..., description="User email for authentication"),
    db: Session = Depends(get_db)
):
    authenticate_user(email, db)
    event = db.query(Event).filter(Event.id == event_id).first()
    if not event:
        raise HTTPException(status_code=404, detail="Event not found")
    db.delete(event)
    db.commit()
    return {"message": "Event deleted successfully"}