from bson import ObjectId
from motor.motor_asyncio import AsyncIOMotorCollection

from domain.phone import sanitize_phone


class MongoClientRepository:
    def __init__(self, collection: AsyncIOMotorCollection):
        self._clients = collection

    async def resolve_or_create(self, salon_id: str, phone: str) -> str:
        salon_oid = ObjectId(salon_id)
        sanitized = sanitize_phone(phone)
        if not sanitized:
            raise ValueError("Invalid client phone number")

        existing = await self._clients.find_one(
            {"phone": sanitized, "salonId": salon_oid},
            {"_id": 1},
        )
        if existing:
            return str(existing["_id"])

        result = await self._clients.insert_one(
            {
                "name": "Unknown",
                "phone": sanitized,
                "salonId": salon_oid,
                "status": "new",
            }
        )
        return str(result.inserted_id)
