from fastapi import APIRouter, Depends, HTTPException, Form, status
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.auth import verify_password, create_access_token
from app.schemas.trip import TripResponse
from app.schemas.auth import TripAuthRequest, TripAuthResponse
from app.models.trip import Trip

router = APIRouter()

@router.post("/trip/authenticate", response_model=TripAuthResponse)
async def authenticate_trip(auth_request: TripAuthRequest, db: Session = Depends(get_db)):
    """Authenticate with trip password and get access token"""
    trip = db.query(Trip).filter(Trip.id == auth_request.trip_id, Trip.is_active == "active").first()
    
    if not trip:
        raise HTTPException(status_code=404, detail="Trip not found")
    
    # If trip has no password, return error (shouldn't call this endpoint)
    if trip.password_hash is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="This trip does not require a password"
        )
    
    # Verify password
    if not verify_password(auth_request.password, trip.password_hash):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect password"
        )
    
    # Create access token
    access_token = create_access_token(data={"trip_id": trip.id})
    
    return TripAuthResponse(
        access_token=access_token,
        token_type="bearer",
        trip_id=trip.id
    )


@router.get("/trip/{share_code}")
async def get_trip_by_share_code(share_code: str, db: Session = Depends(get_db)):
    """Get trip details by share code for anonymous users"""
    from app.models.trip import Trip
    from app.models.participant import Participant

    trip = db.query(Trip).filter(Trip.share_code == share_code, Trip.is_active == "active").first()
    if not trip:
        raise HTTPException(status_code=404, detail="Trip not found")

    # Get participants for this trip
    participants = db.query(Participant).filter(
        Participant.trip_id == trip.id,
        Participant.is_active == True
    ).all()

    return {
        "trip": TripResponse.from_orm(trip),
        "participants": [
            {"id": p.id, "name": p.name, "is_creator": p.is_creator}
            for p in participants
        ]
    }

@router.post("/identify")
async def identify_user(
    trip_id: int = Form(...),
    participant_id: int = Form(...),
    device_id: str = Form(...),
    db: Session = Depends(get_db)
):
    """Identify user and link device ID to participant"""
    from app.models.participant import Participant

    participant = db.query(Participant).filter(
        Participant.id == participant_id,
        Participant.trip_id == trip_id,
        Participant.is_active == True
    ).first()

    if not participant:
        raise HTTPException(status_code=404, detail="Participant not found")

    # Update device ID for this participant
    participant.device_id = device_id
    from sqlalchemy import text
    from datetime import datetime
    participant.last_accessed = datetime.utcnow()
    db.commit()

    return {"message": "User identified successfully", "participant_name": participant.name}