from fastapi import APIRouter, Depends, HTTPException, status, Form, File, UploadFile
from sqlmodel import Session, select
from typing import List, Optional
from app.core.database import get_session
from app.models.business import Business
from app.models.user import User, UserRole
from app.api.deps import get_current_user

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

@router.get("", response_model=List[Business])
async def list_businesses(
    *,
    session: Session = Depends(get_session)
):
    """List all businesses."""
    statement = select(Business)
    businesses = session.exec(statement).all()
    return businesses

@router.post("", response_model=Business)
async def create_business(
    *,
    session: Session = Depends(get_session),
    name: str = Form(...),
    category: str = Form(...),
    address: str = Form(...),
    phone: Optional[str] = Form(None),
    social_media: Optional[str] = Form(None),
    latitude: Optional[float] = Form(None),
    longitude: Optional[float] = Form(None),
    image: Optional[UploadFile] = File(None),
    current_user: User = Depends(get_current_user)
):
    """Create a new business (Promoters and Admins only)."""
    if current_user.role not in [UserRole.ADMIN, UserRole.PROMOTER]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only promoters and admins can manage businesses"
        )
    
    image_url = None
    if image:
        import os
        import shutil
        from uuid import uuid4
        UPLOAD_DIR = "uploads/businesses"
        os.makedirs(UPLOAD_DIR, exist_ok=True)
        ext = os.path.splitext(image.filename)[1]
        filename = f"{uuid4()}{ext}"
        path = os.path.join(UPLOAD_DIR, filename)
        with open(path, "wb") as buffer:
            shutil.copyfileobj(image.file, buffer)
        image_url = f"/uploads/businesses/{filename}"
    
    db_business = Business(
        name=name,
        category=category,
        address=address,
        phone=phone,
        social_media=social_media,
        latitude=latitude,
        longitude=longitude,
        image_url=image_url
    )
    session.add(db_business)
    session.commit()
    session.refresh(db_business)
    return db_business

@router.patch("/{business_id}", response_model=Business)
async def update_business(
    *,
    session: Session = Depends(get_session),
    business_id: str,
    name: Optional[str] = Form(None),
    category: Optional[str] = Form(None),
    address: Optional[str] = Form(None),
    phone: Optional[str] = Form(None),
    social_media: Optional[str] = Form(None),
    latitude: Optional[float] = Form(None),
    longitude: Optional[float] = Form(None),
    image: Optional[UploadFile] = File(None),
    current_user: User = Depends(get_current_user)
):
    """Update a business (Promoters and Admins only)."""
    if current_user.role not in [UserRole.ADMIN, UserRole.PROMOTER]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only promoters and admins can manage businesses"
        )
    
    db_business = session.get(Business, business_id)
    if not db_business:
        raise HTTPException(status_code=404, detail="Business not found")
    
    if name is not None:
        db_business.name = name
    if category is not None:
        db_business.category = category
    if address is not None:
        db_business.address = address
    if phone is not None:
        db_business.phone = phone
    if social_media is not None:
        db_business.social_media = social_media
    if latitude is not None:
        db_business.latitude = latitude
    if longitude is not None:
        db_business.longitude = longitude
    
    if image:
        import os
        import shutil
        from uuid import uuid4
        UPLOAD_DIR = "uploads/businesses"
        os.makedirs(UPLOAD_DIR, exist_ok=True)
        ext = os.path.splitext(image.filename)[1]
        filename = f"{uuid4()}{ext}"
        path = os.path.join(UPLOAD_DIR, filename)
        with open(path, "wb") as buffer:
            shutil.copyfileobj(image.file, buffer)
        db_business.image_url = f"/uploads/businesses/{filename}"
    
    session.add(db_business)
    session.commit()
    session.refresh(db_business)
    return db_business

@router.get("/{business_id}", response_model=Business)
async def get_business(business_id: str, session: Session = Depends(get_session)):
    """Get a single business by ID."""
    business = session.get(Business, business_id)
    if not business:
        raise HTTPException(status_code=404, detail="Business not found")
    return business

@router.delete("/{business_id}")
async def delete_business(
    *,
    session: Session = Depends(get_session),
    business_id: str,
    current_user: User = Depends(get_current_user)
):
    """Delete a business (Promoters and Admins only)."""
    if current_user.role not in [UserRole.ADMIN, UserRole.PROMOTER]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only promoters and admins can manage businesses"
        )
    
    db_business = session.get(Business, business_id)
    if not db_business:
        raise HTTPException(status_code=404, detail="Business not found")
    
    session.delete(db_business)
    session.commit()
    return {"status": "success", "message": "Business deleted"}
