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()

        result = await collection.insert_one(otp_dict)

        return str(result.inserted_id)

    async def get_active_otp_by_phone(
        self,
        country_code: str,
        phone: str,
        purpose: str
    ):
        collection = self.get_collection()

        otp = await collection.find_one(
            {
                "country_code": country_code,
                "phone": phone,
                "purpose": purpose,
                "is_active": True
            }
        )

        return otp

    async def expire_otp(self, otp_id: str):

        collection = self.get_collection()

        if not ObjectId.is_valid(otp_id):
            return False

        result = await collection.update_one(
            {
                "_id": ObjectId(otp_id)
            },
            {
                "$set": {
                    "is_active": False
                }
            }
        )

        return result.modified_count > 0

