from app.db import database
from pymongo import ReturnDocument
from enum import Enum

def get_next_sequence_value(sequence_name: str, db: database.MongoDB) -> int:
    ret = db["counters"].find_one_and_update(
        {"_id": sequence_name},
        {"$inc": {"sequence_value": 1}},
        upsert=True,
        return_document=ReturnDocument.AFTER
    )
    # If the sequence is less than 100001, set it to 100001.
    if ret["sequence_value"] < 100001:
        db["counters"].update_one(
            {"_id": sequence_name},
            {"$set": {"sequence_value": 100001}}
        )
        return 100001
    return ret["sequence_value"]

def get_next_sequence_value_int(sequence_name: str, db):
    sequence_doc = db.counters.find_one_and_update(
        {"_id": sequence_name},
        {"$inc": {"sequence_value": 1}},
        return_document=True,
        upsert=True
    )

    # If the sequence_doc is None (very rare) or lacks the field, return 1
    return sequence_doc.get("sequence_value", 1)

def get_next_sequence_value(sequence_name: str, db: database.MongoDB) -> int:
    ret = db["counters"].find_one_and_update(
        {"_id": sequence_name},
        {"$inc": {"sequence_value": 1}},
        upsert=True,
        return_document=ReturnDocument.AFTER
    )
    # If the sequence is less than 100001, set it to 100001.
    if ret["sequence_value"] < 100001:
        db["counters"].update_one(
            {"_id": sequence_name},
            {"$set": {"sequence_value": 100001}}
        )
        return 100001
    return ret["sequence_value"]



def convert_enums(obj):
    # Recursively convert enum values in dict or list objects
    if isinstance(obj, dict):
        return {k: convert_enums(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [convert_enums(v) for v in obj]
    elif isinstance(obj, Enum):
        return obj.value
    else:
        return obj
