import uuid
from datetime import datetime

from pydantic import BaseModel, Field

from app.models.user import UserRole


class LdapConfigCreate(BaseModel):
    host: str = Field(min_length=1, max_length=255)
    port: int = Field(default=389, ge=1, le=65535)
    use_ssl: bool = False
    use_tls: bool = False
    tls_verify: bool = False
    bind_dn: str = Field(min_length=1)
    bind_password: str = Field(min_length=1)
    base_dn: str = Field(min_length=1)
    user_search_filter: str = Field(default="(objectClass=person)", min_length=1, max_length=512)
    attr_email: str = Field(default="mail", min_length=1, max_length=100)
    attr_firstname: str = Field(default="givenName", min_length=1, max_length=100)
    attr_lastname: str = Field(default="sn", min_length=1, max_length=100)
    attr_username: str = Field(default="sAMAccountName", min_length=1, max_length=100)
    attr_department: str | None = Field(default=None, max_length=100)
    attr_personnel_number: str | None = Field(default=None, max_length=100)
    enabled: bool = False


class LdapConfigUpdate(BaseModel):
    host: str | None = Field(default=None, min_length=1, max_length=255)
    port: int | None = Field(default=None, ge=1, le=65535)
    use_ssl: bool | None = None
    use_tls: bool | None = None
    tls_verify: bool | None = None
    bind_dn: str | None = None
    bind_password: str | None = None
    base_dn: str | None = None
    user_search_filter: str | None = Field(default=None, max_length=512)
    attr_email: str | None = Field(default=None, max_length=100)
    attr_firstname: str | None = Field(default=None, max_length=100)
    attr_lastname: str | None = Field(default=None, max_length=100)
    attr_username: str | None = Field(default=None, max_length=100)
    attr_department: str | None = Field(default=None, max_length=100)
    attr_personnel_number: str | None = Field(default=None, max_length=100)
    enabled: bool | None = None


class LdapConfigOut(BaseModel):
    model_config = {"from_attributes": True}

    id: uuid.UUID
    company_id: uuid.UUID
    enabled: bool
    host: str
    port: int
    use_ssl: bool
    use_tls: bool
    tls_verify: bool
    bind_dn: str
    base_dn: str
    user_search_filter: str
    attr_email: str
    attr_firstname: str
    attr_lastname: str
    attr_username: str
    attr_department: str | None
    attr_personnel_number: str | None = None
    last_sync_at: datetime | None
    created_at: datetime
    updated_at: datetime


class LdapTestResult(BaseModel):
    success: bool
    message: str


class LdapSyncRequest(BaseModel):
    default_role: UserRole = UserRole.EMPLOYEE


class LdapSyncResult(BaseModel):
    created: int
    updated: int
    deactivated: int
    errors: list[str]


class LdapUserPreview(BaseModel):
    dn: str
    email: str
    first_name: str
    last_name: str
    department: str | None = None
