from bson import ObjectId
from app.config.DB import db_manager
from app.modules.otp.otp_model import OtpModel

class OtpRepository:

    def __init__(self):
        self.collection_name = "otp"

    def get_collection(self):
        return db_manager.db[self.collection_name]

    async def add_otp(self, otp: OtpModel):
        collection = self.get_collection()

        otp_dict = otp.model_dump()  # Pydantic v2

        result = await collection.insert_one(otp_dict)

        return str(result.inserted_id)
    
    async def get_active_otp_by_phone(self, phone: str):
        collection = self.get_collection()

        otp = await collection.find_one({
            "phone": phone,
            "is_active": True
        })

        return otp
    
    async def expire_otp(self, otp_id: str):
        collection = self.get_collection()

        result = await collection.update_one(
            {"_id": ObjectId(otp_id)},
            {
                "$set": {
                    "is_active": False
                }
            }
        )

        return result.modified_count > 0