from pydantic import BaseModel, Field
from typing import Optional, Union, List
from enum import Enum
from datetime import datetime
from bson import ObjectId


class EntityType(str, Enum):
    vehicle = "vehicle"
    workforce = "workforce"


class GeofenceRuleMappingBase(BaseModel):
    account_id: str
    user_id: Optional[str] = None
    geofence_id: Optional[str] = None
    geofence_name: Optional[str] = None
    rule_name: Optional[str] = None
    geofence_rule_id: Optional[str] = None
    assigned_entity_type: Optional[EntityType] = None
    assigned_entity_id: Optional[List[str]] = None

    model_config = {
        "arbitrary_types_allowed": True  # ✅ This allows ObjectId to be used
    }


class GeofenceRuleMappingCreate(GeofenceRuleMappingBase):
    pass


class GeofenceRuleMappingUpdate(BaseModel):
    user_id: Optional[str] = None
    geofence_id: Optional[Union[str, ObjectId]] = None
    geofence_rule_id: Optional[Union[str, ObjectId]] = None
    assigned_entity_type: Optional[EntityType] = None
    assigned_entity_id: Optional[List[str]] = None
    geofence_name: Optional[str] = None
    rule_name: Optional[str] = None

    model_config = {
        "arbitrary_types_allowed": True
    }


class GeofenceRuleMapping(GeofenceRuleMappingBase):
    id: Optional[str] = None
    created_date: datetime = Field(default_factory=datetime.utcnow)

    model_config = {
        "populate_by_name": True,
        "arbitrary_types_allowed": True,
        "json_encoders": {ObjectId: str},
    }


class GeofenceRuleMappings(BaseModel):
    total_count: int
    users: List[GeofenceRuleMapping]

    model_config = {
        "arbitrary_types_allowed": True,
    }
