from fastapi import APIRouter, Depends, status, UploadFile, File, Form, HTTPException
from typing import List, Optional
import os
import logging
from sqlalchemy.ext.asyncio import AsyncSession

from app.database.database import get_db
from app.utils.auth import get_customer_or_staff_user
from app.schemas.user.feedback_schemas import FeedbackResponse
from app.services.user.feedback_service import FeedbackService
from app.utils.s3 import upload_file_to_s3

logger = logging.getLogger(__name__)


router = APIRouter()


@router.post("/feedbacks", response_model=FeedbackResponse, status_code=status.HTTP_201_CREATED)
async def create_feedback(
    subject: str = Form(..., description="Feedback subject"),
    description: str = Form(..., description="Feedback description"),
    images: List[UploadFile] = File(default=[], description="One or more image files to attach to the feedback (optional)"),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(get_customer_or_staff_user)
):
    # Validate and upload images (if any) to S3
    image_urls: List[str] = []
    
    if images:
        allowed_extensions = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg"}
        max_size = 10 * 1024 * 1024  # 10MB per file

        for image in images:
            if not image.filename or not image.filename.strip():
                continue
                
            try:
                file_extension = os.path.splitext(image.filename)[1].lower()
                if file_extension not in allowed_extensions:
                    raise HTTPException(
                        status_code=status.HTTP_400_BAD_REQUEST,
                        detail=f"File type not allowed for '{image.filename}'. "
                        f"Allowed types: {', '.join(allowed_extensions)}"
                    )

                file_content = await image.read()
                if len(file_content) == 0:
                    continue
                    
                if len(file_content) > max_size:
                    raise HTTPException(
                        status_code=status.HTTP_400_BAD_REQUEST,
                        detail=f"File '{image.filename}' exceeds maximum size of 10MB"
                    )

                # Upload to S3 under a dedicated feedback folder
                file_url = upload_file_to_s3(file_content, image.filename, folder="feedback")
                if file_url:
                    image_urls.append(file_url)
            except HTTPException:
                raise
            except Exception as e:
                logger.error(f"Error uploading image '{image.filename}': {str(e)}", exc_info=True)
                continue

    # Determine if it's a customer or staff based on token
    user_id = None
    staff_id = None
    
    if current_user.get("user_type") == "customer":
        user_id = int(current_user["sub"])
    else:
        # It's staff (EMPLOYEE, MANAGER, ADMIN, or SUPERADMIN)
        staff_id = int(current_user["sub"])

    service = FeedbackService(db)
    feedback = await service.create_feedback(
        subject=subject,
        description=description,
        user_id=user_id,
        staff_id=staff_id,
        image_urls=image_urls or None,
    )
    return feedback


