# models.py
from beanie import Document, Link
from typing import Optional
from datetime import datetime, timezone
import re
from uuid import UUID, uuid4
from pydantic import Field, EmailStr

class User(Document):
    id: UUID = Field(default_factory=uuid4)
    name: str = Field(..., unique=False)  # 이름은 유니크하지 않을 수 있음
    email: EmailStr = Field(..., unique=True)  # 이메일은 유니크
    company: Optional[str] = None
    position: Optional[str] = None
    phone_number: str = Field(..., pattern=r'^\d{10,15}$', unique=True)  # 유니크 인덱스 설정
    
    class Settings:
        name = "users"
        indexes = [
            "email",
            "phone_number"
        ]
        
    @classmethod
    def validate_phone_number(cls, phone_number: str) -> bool:
        # 전화번호 형식 검증 (숫자만, 10~15자리)
        pattern = re.compile(r'^\d{10,15}$')
        return bool(pattern.match(phone_number))
    
class Booth(Document):
    id: UUID = Field(default_factory=uuid4)
    name: str = Field(..., unique=True)  # unique=True로 유니크 인덱스 설정
    qr_code: str = Field(..., unique=True)  # unique=True로 유니크 인덱스 설정

    class Settings:
        name = "booths"
        # 인덱스 정의 (추가적으로 설정할 수 있습니다)
        indexes = [
            "name",
            "qr_code"
        ]

class ScanRecord(Document):
    id: UUID = Field(default_factory=uuid4)
    user_id: Link[User]  # Link to User
    booth_id: Link[Booth]  # Link to Booth
    timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))

    class Settings:
        name = "scan_records"
        # indexes = [
            # [("user_id", 1), ("booth_id", 1)],  # 유니크 인덱스 설정
        # ]
        unique_indexes = [
            [("user_id", 1), ("booth_id", 1)]  # 유니크 인덱스 설정
        ]