from datetime import datetime

from pydantic import BaseModel, Field, validator
from typing import Optional, List

from intranet.domenator.src.logic.domain import (
    from_punycode,
    to_punycode,
)


class WhoIsOutSchema(BaseModel):
    org_id: int
    type: str = 'domain'
    object_id: str = Field(..., alias='name')

    class Config:
        orm_mode = True


class OwnershipInfoOutSchema(BaseModel):
    domain: str
    status: str
    preferred_host: str
    methods: Optional[List[dict]]
    last_check: Optional[dict]


class CheckOwnershipOutSchema(BaseModel):
    domain: str = Field(..., alias='name')
    owned: bool

    class Config:
        orm_mode = True


class CheckOwnershipInSchema(BaseModel):
    verification_type: str


class DomainOutSchema(BaseModel):
    org_id: Optional[int]
    name: Optional[str]
    owned: Optional[bool]
    master: Optional[bool]
    tech: Optional[bool]
    mx: Optional[bool]
    delegated: Optional[bool]
    display: Optional[bool]
    validated: Optional[bool]
    via_webmaster: Optional[bool]
    created_at: Optional[datetime]
    validated_at: Optional[datetime]

    class Config:
        orm_mode = True

    @validator("name")
    def decode_from_punycode(cls, name: str):
        return from_punycode(name)


class DomainHistoryOutSchema(BaseModel):
    id: int
    org_id: str
    name: str
    action: str
    author_id: Optional[str]
    timestamp: datetime

    class Config:
        orm_mode = True


class DomainAddInSchema(BaseModel):
    org_id: str
    domain: str
    admin_uid: str

    @validator("domain")
    def encode_to_punycode(cls, domain: str):
        return to_punycode(domain.lower())


class OwnedDomainAddInSchema(BaseModel):
    domain: str
    org_id: str
    admin_id: str

    @validator("domain")
    def encode_to_punycode(cls, domain: str):
        return to_punycode(domain.lower())


class DomainSyncInSchema(BaseModel):
    org_id: str
    admin_id: str


class UpdateAdminInSchema(BaseModel):
    admin_id: str
