"""User schema module."""

from typing import Optional
from uuid import UUID

from pydantic import BaseModel, EmailStr, Field, field_validator

from airweave.schemas.organization import Organization


class UserOrganizationBase(BaseModel):
    """Base schema for UserOrganization relationship."""

    role: str = "member"  # owner, admin, member
    is_primary: bool = False
    user_id: UUID
    organization_id: UUID

    class Config:
        """Pydantic config for UserOrganizationBase."""

        from_attributes = True


class UserOrganization(UserOrganizationBase):
    """Schema for UserOrganization relationship with full organization details."""

    organization: Organization

    class Config:
        """Pydantic config for UserOrganization."""

        from_attributes = True


class UserBase(BaseModel):
    """Base schema for User."""

    email: EmailStr
    full_name: Optional[str] = "Superuser"

    class Config:
        """Pydantic config for UserBase."""

        from_orm = True
        from_attributes = True


class UserCreate(UserBase):
    """Schema for creating a User object."""

    auth0_id: Optional[str] = None


class UserUpdate(UserBase):
    """Schema for updating a User object."""

    auth0_id: Optional[str] = None
    permissions: Optional[list[str]] = None


class UserInDBBase(UserBase):
    """Base schema for User stored in DB."""

    id: UUID
    auth0_id: Optional[str] = None
    primary_organization_id: Optional[UUID] = None
    user_organizations: list[UserOrganization] = Field(default_factory=list)
    is_admin: bool = False

    @field_validator("user_organizations", mode="before")
    @classmethod
    def load_organizations(cls, v):
        """Ensure organizations are always loaded."""
        return v or []

    @property
    def primary_organization(self) -> Optional[UserOrganization]:
        """Get the primary organization for this user."""
        for org in self.user_organizations:
            if org.is_primary:
                return org
        return None

    @property
    def organization_roles(self) -> dict[UUID, str]:
        """Get a mapping of organization IDs to roles."""
        return {org.organization.id: org.role for org in self.user_organizations}

    class Config:
        """Pydantic config for UserInDBBase."""

        from_attributes = True


class User(UserInDBBase):
    """Schema for User."""

    class Config:
        """Pydantic config for User."""

        from_attributes = True
        populate_by_name = True


class UserInDB(UserInDBBase):
    """Schema for User stored in DB."""

    hashed_password: Optional[str] = None


class UserWithOrganizations(UserInDBBase):
    """Schema for User with Organizations - now redundant as all users include orgs."""

    pass
