from datetime import datetime
from typing import List, Optional
from ninja import Schema
from pydantic import EmailStr, Field


class TokenSchema(Schema):
    access_token: str
    token_type: str = "bearer"


class UserBase(Schema):
    email: EmailStr
    username: str = Field(min_length=3, max_length=50)
    avatar: Optional[str] = None
    bio: Optional[str] = None


class UserCreate(UserBase):
    password: str = Field(min_length=8)


class UserOut(UserBase):
    id: int
    username: str
    email: str
    avatar: Optional[str] = None
    bio: Optional[str] = None
    created_at: datetime


class UserUpdate(Schema):
    username: Optional[str] = None
    email: Optional[str] = None
    avatar: Optional[str] = None
    bio: Optional[str] = None


class LoginSchema(Schema):
    email: EmailStr
    password: str


class CategoryBase(Schema):
    name: str = Field(min_length=1, max_length=100)
    description: Optional[str] = None


class CategoryOut(Schema):
    id: int
    name: str
    description: str = None


class TagBase(Schema):
    name: str = Field(min_length=1, max_length=50)


class TagOut(TagBase):
    id: int
    created_at: datetime


class PostBase(Schema):
    title: str = Field(min_length=1, max_length=200)
    content: str
    summary: Optional[str] = None
    category_id: int
    tag_ids: List[int] = []


class PostCreate(PostBase):
    pass


class PostUpdate(Schema):
    title: Optional[str] = Field(None, min_length=1, max_length=200)
    content: Optional[str] = None
    summary: Optional[str] = None
    category_id: Optional[int] = None
    tag_ids: Optional[List[int]] = None


class PostOut(PostBase):
    id: int
    author: UserOut
    category: CategoryOut
    tags: List[TagOut]
    created_at: datetime
    updated_at: datetime
    likes_count: int
    comments_count: int


class CommentBase(Schema):
    content: str
    post_id: int
    parent_id: Optional[int] = None


class CommentCreate(CommentBase):
    pass


class CommentUpdate(Schema):
    content: str


class CommentOut(Schema):
    id: int
    content: str
    author: UserOut
    post_id: int
    parent_id: Optional[int]
    created_at: datetime
    updated_at: datetime
    likes_count: int
    replies_count: int


class LikeCreate(Schema):
    post_id: Optional[int] = None
    comment_id: Optional[int] = None


class ErrorMessage(Schema):
    detail: str
