import bson
from pydantic import field_validator, Field, BaseModel as PydanticBaseModel

from panther.configs import config
from panther.db.queries import Query


if config['db_engine'] == 'pantherdb':
    IDType = int
else:
    IDType = str


class Model(PydanticBaseModel, Query):
    id: IDType | None = Field(validation_alias='_id')

    @field_validator('id', mode='before')
    def validate_id(cls, value):
        if isinstance(value, str):
            try:
                bson.ObjectId(value)
            except Exception:
                raise ValueError('Invalid ObjectId')
        elif not isinstance(value, bson.ObjectId):
            raise ValueError('ObjectId required')
        return str(value)

    @property
    def _id(self):
        if IDType is int:
            return self.id
        else:
            return bson.ObjectId(self.id) if self.id else None


class BaseUser(Model):
    first_name: str | None
    last_name: str | None
