from fastapi import APIRouter, HTTPException, status, Depends, UploadFile, File
from app.schemas import PhotoResponse, PhotoUploadResponse
from app.services.photo_service import PhotoService
from app.auth import get_current_user
from app.db import get_db_connection

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

@router.post("/upload", response_model=PhotoUploadResponse)
async def upload_photo(
    file: UploadFile = File(...),
    current_user: dict = Depends(get_current_user)
):
    """Upload a profile photo"""
    try:
        # Get user's profile ID
        with get_db_connection() as conn:
            cur = conn.cursor()
            cur.execute("SELECT id FROM profiles WHERE user_id = %s", (current_user["user_id"],))
            row = cur.fetchone()
            if not row:
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="Profile not found"
                )
            profile_id = row[0]
        
        # Read and save file
        content = await file.read()
        return PhotoService.upload_photo(profile_id, content, file.filename)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )

@router.get("/{photo_id}", response_model=PhotoResponse)
def get_photo_info(photo_id: int, current_user: dict = Depends(get_current_user)):
    """Get photo metadata"""
    with get_db_connection() as conn:
        cur = conn.cursor()
        cur.execute(
            "SELECT id, profile_id, file_path, display_order FROM photos WHERE id = %s",
            (photo_id,)
        )
        row = cur.fetchone()
        if not row:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Photo not found"
            )
        return PhotoResponse(id=row[0], profile_id=row[1], file_path=row[2], display_order=row[3])

@router.delete("/{photo_id}")
def delete_photo(photo_id: int, current_user: dict = Depends(get_current_user)):
    """Delete a photo"""
    with get_db_connection() as conn:
        cur = conn.cursor()
        cur.execute(
            "SELECT profile_id FROM photos WHERE id = %s",
            (photo_id,)
        )
        row = cur.fetchone()
        if not row:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Photo not found"
            )
        
        profile_id = row[0]
        
        # Verify ownership
        cur.execute("SELECT user_id FROM profiles WHERE id = %s", (profile_id,))
        owner = cur.fetchone()
        if not owner or owner[0] != current_user["user_id"]:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Not authorized"
            )
    
    if PhotoService.delete_photo(photo_id, profile_id):
        return {"message": "Photo deleted"}
    else:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Could not delete photo"
        )
