"""
Files router module.

This module provides API endpoints for file management operations including
upload, download, listing, and deletion of files.
"""

from typing import List, Dict, Any, Optional
from fastapi import APIRouter, Depends, Query, UploadFile, File, Form, HTTPException, status
from sqlalchemy.orm import Session
from starlette.responses import Response

from src.core.database import get_db
from src.apps.auth.utils.auth import get_current_active_user
from src.apps.users.models.user import User
from src.apps.files import file_services
from src.core.utils.enums import FileTypes

router = APIRouter()


@router.get("/")
async def list_files(
    *,
    db: Session = Depends(get_db),
    ids: str = "",
    page: int = 1,
    per_page: int = 20,
    current_user: User = Depends(get_current_active_user),
) -> Dict[str, Any]:
    """
    List all available files for the requesting user.
    """
    try:
        response = await file_services.list_user_files(
            db=db,
            ids=ids,
            skip=((page - 1) * per_page),
            limit=per_page,
            created_by=current_user,
        )
        return {"data": response, "message": "File list"}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.get("/download", response_model=None)
async def download_file_by_path(
    *,
    filepath: str = Query(description="Path of the file to download"),
    db: Session = Depends(get_db),
    current_user: Optional[User] = Depends(get_current_active_user),
) -> Response:
    """
    Download a file by its path or storage key.
    """
    try:
        response = file_services.download_file_by_path(
            db=db, path=filepath, current_user=current_user
        )
        return response
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )


@router.get("/{file_id}")
async def get_file_by_id(
    *,
    file_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user),
) -> Dict[str, Any]:
    """
    Fetch a file resource by its ID.
    """
    try:
        response = await file_services.get_file_by_id(
            db=db, file_id=file_id, created_by=current_user
        )
        return {"data": response, "message": "File details"}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )


@router.post("/upload-one")
async def upload_single_file(
    *,
    file: UploadFile = File(...),
    file_type: str = Form(default="document"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user),
) -> Dict[str, Any]:
    """
    Upload a single file to the server.
    """
    try:
        # Create a simple merchant object for backward compatibility
        class SimpleMerchant:
            def __init__(self, merchant_id: str):
                self.merchant_id = merchant_id
        
        # Use user ID as merchant ID for simplicity
        merchant = SimpleMerchant(str(current_user.id))
        
        response = await file_services.upload_single_file(
            db=db,
            file=file,
            file_type=file_type,
            created_by=current_user,
            merchant=merchant,
        )
        return {"data": response, "message": "File uploaded successfully"}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.post("/upload-many")
async def upload_multiple_files(
    *,
    files: List[UploadFile] = File(...),
    file_type: str = Form(default="document"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user),
) -> Dict[str, Any]:
    """
    Upload multiple files to the server.
    """
    try:
        # Create a simple merchant object for backward compatibility
        class SimpleMerchant:
            def __init__(self, merchant_id: str):
                self.merchant_id = merchant_id
        
        # Use user ID as merchant ID for simplicity
        merchant = SimpleMerchant(str(current_user.id))
        
        response = await file_services.upload_multiple_files(
            db=db,
            files=files,
            file_type=file_type,
            created_by=current_user,
            merchant=merchant,
        )
        return {"data": response, "message": "Files uploaded successfully"}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.delete("/{file_id}")
async def delete_file_by_id(
    *,
    file_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user),
) -> Dict[str, Any]:
    """
    Delete a file resource by its ID.
    """
    try:
        response = await file_services.delete_file_by_id(
            db=db, file_id=file_id, created_by=current_user
        )
        return {"data": response, "message": "File removed successfully"}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )