from fastapi import APIRouter, HTTPException, Depends
from typing import List
from models.schemas import Special, SpecialCreate, SpecialUpdate
from auth import get_current_admin
import uuid
from datetime import datetime

router = APIRouter(prefix="/api/specials", tags=["Specials"])

# MongoDB connection will be injected
db = None

def set_db(database):
    global db
    db = database

@router.get("", response_model=List[Special])
async def get_specials():
    """Get all weekly specials"""
    specials = await db.specials.find({}, {'_id': 0}).limit(100).to_list(100)
    
    # Convert MongoDB _id to id for response
    for special in specials:
        if "_id" in special:
            del special["_id"]
    
    return specials

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

@router.post("", response_model=Special)
async def create_special(
    special: SpecialCreate,
    admin: dict = Depends(get_current_admin)
):
    """Add a destination to specials (admin only)"""
    # Check if destination exists
    destination = await db.destinations.find_one({"id": special.destination_id})
    if not destination:
        raise HTTPException(status_code=404, detail="Destination not found")
    
    # Check if special already exists for this destination
    existing = await db.specials.find_one({"destination_id": special.destination_id})
    if existing:
        raise HTTPException(status_code=400, detail="Special already exists for this destination")
    
    special_data = special.dict()
    special_data["id"] = str(uuid.uuid4())
    special_data["created_at"] = datetime.utcnow()
    
    await db.specials.insert_one(special_data)
    
    if "_id" in special_data:
        del special_data["_id"]
    
    return special_data

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

@router.delete("/destination/{destination_id}")
async def delete_special_by_destination(
    destination_id: str,
    admin: dict = Depends(get_current_admin)
):
    """Remove a destination from specials (admin only)"""
    result = await db.specials.delete_one({"destination_id": destination_id})
    
    if result.deleted_count == 0:
        raise HTTPException(status_code=404, detail="Special not found for this destination")
    
    return {"message": "Special removed successfully"}
