from fastapi import APIRouter, HTTPException

from vdash.modules.user_db import (
    CreateUserDBRequest,
    UpdateUserDBRequest,
    UserDBResponse,
)
from vdash.shared import MessageResponse, PaginatedResult

from ..dependencies import CryptoHelperDep, PaginationQueryDep, UserDBServiceDep

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


@router.get("/", response_model=PaginatedResult[UserDBResponse])
async def list_databases(
    service: UserDBServiceDep,
    crypto: CryptoHelperDep,
    pagination: PaginationQueryDep,
):
    user_dbs = await service.list_user_dbs(pagination)

    return PaginatedResult[UserDBResponse](
        items=[
            UserDBResponse(
                uuid=user_db.uuid,
                name=user_db.name,
                connection_string=crypto.decrypt_connection_string(
                    user_db.connection_string
                ),
                created_at=user_db.created_at,
                updated_at=user_db.updated_at,
            )
            for user_db in user_dbs.items
        ],
        page=user_dbs.page,
        page_size=user_dbs.page_size,
        total=user_dbs.total,
    )


@router.post("/", response_model=UserDBResponse)
async def create_database(
    request: CreateUserDBRequest,
    service: UserDBServiceDep,
    crypto: CryptoHelperDep,
):
    user_db = await service.create_user_db(request)
    connection_string = crypto.decrypt_connection_string(user_db.connection_string)

    return UserDBResponse(
        uuid=user_db.uuid,
        name=user_db.name,
        connection_string=connection_string,
        created_at=user_db.created_at,
        updated_at=user_db.updated_at,
    )


@router.get(
    "/{uuid}",
    response_model=UserDBResponse,
    responses={404: {"description": "Not Found"}},
)
async def get_database(
    uuid: str,
    service: UserDBServiceDep,
    crypto: CryptoHelperDep,
):
    user_db = await service.get_user_db(uuid)
    if user_db is None:
        raise HTTPException(status_code=404, detail="Database not found")

    connection_string = crypto.decrypt_connection_string(user_db.connection_string)

    return UserDBResponse(
        uuid=user_db.uuid,
        name=user_db.name,
        connection_string=connection_string,
        created_at=user_db.created_at,
        updated_at=user_db.updated_at,
    )


@router.put(
    "/{uuid}",
    response_model=UserDBResponse,
    responses={404: {"description": "Not Found"}},
)
async def update_database(
    uuid: str,
    request: UpdateUserDBRequest,
    service: UserDBServiceDep,
    crypto: CryptoHelperDep,
):
    user_db = await service.update_user_db(uuid, request)
    if user_db is None:
        raise HTTPException(status_code=404, detail="Database not found")

    connection_string = crypto.decrypt_connection_string(user_db.connection_string)

    return UserDBResponse(
        uuid=user_db.uuid,
        name=user_db.name,
        connection_string=connection_string,
        created_at=user_db.created_at,
        updated_at=user_db.updated_at,
    )


@router.delete(
    "/{uuid}",
    response_model=MessageResponse,
    responses={404: {"description": "Not Found"}},
)
async def delete_database(
    uuid: str,
    service: UserDBServiceDep,
):
    deleted = await service.delete_user_db(uuid)
    if not deleted:
        raise HTTPException(status_code=404, detail="Database not found")

    return MessageResponse(detail="Database deleted successfully")
