from fastapi import APIRouter, HTTPException, Depends
from typing import Any, Dict
from app.db import database
from app.v1.dependencies.auth import get_current_userdetails
from app.v1.models.saas.usersmodel import User
from app.v1.services.crud import (
    create_item_service,
    get_items_service,
    get_item_service,
    update_item_service,
    delete_item_service
)

router = APIRouter()

@router.post("/{collection_name}", response_model=Dict[str, Any])
def create_generic_item(
    collection_name: str,
    payload: Dict[str, Any],
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    try:
        created_item = create_item_service(collection_name, payload, db, current_user)
        return created_item
    except ValueError as ve:
        raise HTTPException(status_code=400, detail=str(ve))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")


@router.get("/{collection_name}", response_model=Dict[str, Any])
def list_generic_items(
    collection_name: str,
    skip: int = 0,
    limit: int = 10,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    result = get_items_service(collection_name, skip, limit, db, current_user)
    return result


@router.get("/{collection_name}/{item_id}", response_model=Dict[str, Any])
def get_generic_item(
    collection_name: str,
    item_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    item = get_item_service(collection_name, item_id, db, current_user)
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item


@router.put("/{collection_name}/{item_id}", response_model=Dict[str, Any])
def update_generic_item(
    collection_name: str,
    item_id: str,
    payload: Dict[str, Any],
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    try:
        updated_item = update_item_service(collection_name, item_id, payload, db, current_user)
        return updated_item
    except ValueError as ve:
        raise HTTPException(status_code=400, detail=str(ve))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")


@router.delete("/{collection_name}/{item_id}", response_model=Dict[str, Any])
def delete_generic_item(
    collection_name: str,
    item_id: str,
    db: database.MongoDB = Depends(database.get_mongo_db),
    current_user: User = Depends(get_current_userdetails)
):
    deleted_item = delete_item_service(collection_name, item_id, db, current_user)
    if deleted_item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return deleted_item
