from fastapi import APIRouter, HTTPException, Depends
from typing import List, Optional
from models.schemas import Destination, DestinationCreate, DestinationUpdate
from auth import get_current_admin
import uuid
from datetime import datetime

router = APIRouter(prefix="/api/destinations", tags=["Destinations"])

# MongoDB connection will be injected
db = None

def set_db(database):
    global db
    db = database

@router.get("", response_model=List[Destination])
async def get_destinations(category: Optional[str] = None, search: Optional[str] = None):
    """Get all destinations with optional filtering"""
    query = {}
    
    if category and category != "All":
        query["category"] = category
    
    if search:
        query["$or"] = [
            {"name": {"$regex": search, "$options": "i"}},
            {"location": {"$regex": search, "$options": "i"}}
        ]
    
    destinations = await db.destinations.find(query, {'_id': 0}).limit(100).to_list(100)
    
    # Convert MongoDB _id to id for response
    for dest in destinations:
        if "_id" in dest:
            del dest["_id"]
    
    return destinations

@router.get("/{destination_id}", response_model=Destination)
async def get_destination(destination_id: str):
    """Get a single destination by ID"""
    destination = await db.destinations.find_one({"id": destination_id})
    
    if not destination:
        raise HTTPException(status_code=404, detail="Destination not found")
    
    if "_id" in destination:
        del destination["_id"]
    
    return destination

@router.post("", response_model=Destination)
async def create_destination(
    destination: DestinationCreate,
    admin: dict = Depends(get_current_admin)
):
    """Create a new destination (admin only)"""
    destination_data = destination.dict()
    destination_data["id"] = str(uuid.uuid4())
    destination_data["created_at"] = datetime.utcnow()
    
    await db.destinations.insert_one(destination_data)
    
    if "_id" in destination_data:
        del destination_data["_id"]
    
    return destination_data

@router.put("/{destination_id}", response_model=Destination)
async def update_destination(
    destination_id: str,
    destination_update: DestinationUpdate,
    admin: dict = Depends(get_current_admin)
):
    """Update a destination (admin only)"""
    # Check if destination exists
    existing = await db.destinations.find_one({"id": destination_id})
    if not existing:
        raise HTTPException(status_code=404, detail="Destination not found")
    
    # Update only provided fields
    update_data = {k: v for k, v in destination_update.dict().items() if v is not None}
    
    if update_data:
        await db.destinations.update_one(
            {"id": destination_id},
            {"$set": update_data}
        )
    
    # Fetch updated destination
    updated = await db.destinations.find_one({"id": destination_id})
    
    if "_id" in updated:
        del updated["_id"]
    
    return updated

@router.delete("/{destination_id}")
async def delete_destination(
    destination_id: str,
    admin: dict = Depends(get_current_admin)
):
    """Delete a destination (admin only)"""
    result = await db.destinations.delete_one({"id": destination_id})
    
    if result.deleted_count == 0:
        raise HTTPException(status_code=404, detail="Destination not found")
    
    # Also delete any specials for this destination
    await db.specials.delete_many({"destination_id": destination_id})
    
    return {"message": "Destination deleted successfully"}
