"""Pydantic schemas for Azure DevOps connections and mirror APIs."""
from __future__ import annotations

from datetime import datetime
from typing import Optional
from uuid import UUID

from pydantic import BaseModel, Field


class AzureConnectionCreate(BaseModel):
    azure_org_url: str = Field(
        ...,
        description="Azure DevOps org URL, e.g. https://dev.azure.com/myorg",
    )
    username: str = Field(
        ...,
        min_length=1,
        max_length=255,
        description="Display label for this connection",
    )
    pat: str = Field(
        ...,
        min_length=1,
        description="Personal Access Token (stored encrypted, never returned)",
    )
    display_name: Optional[str] = Field(None, max_length=255)


class AzureUserConnectionResponse(BaseModel):
    id: UUID
    workspace_id: UUID
    azure_org_url: str
    username: str
    display_name: Optional[str] = None
    auth_type: str = "pat"
    revoked_at: Optional[datetime] = None
    created_at: datetime

    model_config = {"from_attributes": True}


class AzureConnectUrlResponse(BaseModel):
    connect_url: str
    state: str
    callback_return_url: str
    redirect_uri: str


class AzureRepoItem(BaseModel):
    id: str
    full_name: str
    name: str
    project: str
    default_branch: Optional[str] = None
    web_url: Optional[str] = None

    model_config = {"from_attributes": True}


class ProjectAzureMirrorUpsert(BaseModel):
    workspace_user_azure_connection_id: UUID
    target_repo_full_name: str = Field(
        ...,
        min_length=3,
        max_length=512,
        description="Project/RepoName within the Azure org",
    )
    target_default_branch: str = Field(default="main", max_length=100)
    enabled: bool = True


class ProjectAzureMirrorResponse(BaseModel):
    id: UUID
    project_id: UUID
    workspace_user_azure_connection_id: UUID
    target_repo_full_name: str
    target_repo_id: Optional[str] = None
    target_default_branch: str
    enabled: bool
    last_push_sha: Optional[str] = None
    last_error: Optional[str] = None
    target_repo_webhook_id: Optional[str] = None

    model_config = {"from_attributes": True}
