"""
M365 Tenant API router for ClaudeTools.

This module defines all REST API endpoints for managing M365 tenants, including
CRUD operations with proper authentication, validation, and error handling.
"""

from uuid import UUID

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from api.database import get_db
from api.middleware.auth import get_current_user
from api.schemas.m365_tenant import (
    M365TenantCreate,
    M365TenantResponse,
    M365TenantUpdate,
)
from api.services import m365_tenant_service

# Create router with prefix and tags
router = APIRouter()


@router.get(
    "",
    response_model=dict,
    summary="List all M365 tenants",
    description="Retrieve a paginated list of all M365 tenants with optional filtering",
    status_code=status.HTTP_200_OK,
)
def list_m365_tenants(
    skip: int = Query(
        default=0,
        ge=0,
        description="Number of records to skip for pagination"
    ),
    limit: int = Query(
        default=100,
        ge=1,
        le=1000,
        description="Maximum number of records to return (max 1000)"
    ),
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """
    List all M365 tenants with pagination.

    - **skip**: Number of M365 tenants to skip (default: 0)
    - **limit**: Maximum number of M365 tenants to return (default: 100, max: 1000)

    Returns a list of M365 tenants with pagination metadata.

    **Example Request:**
    ```
    GET /api/m365-tenants?skip=0&limit=50
    Authorization: Bearer <token>
    ```

    **Example Response:**
    ```json
    {
        "total": 3,
        "skip": 0,
        "limit": 50,
        "m365_tenants": [
            {
                "id": "123e4567-e89b-12d3-a456-426614174000",
                "client_id": "abc12345-6789-0def-1234-56789abcdef0",
                "tenant_id": "def45678-9abc-0123-4567-89abcdef0123",
                "tenant_name": "dataforth.com",
                "default_domain": "dataforthcorp.onmicrosoft.com",
                "admin_email": "admin@dataforth.com",
                "cipp_name": "Dataforth Corp",
                "notes": "Primary M365 tenant",
                "created_at": "2024-01-15T10:30:00Z",
                "updated_at": "2024-01-15T10:30:00Z"
            }
        ]
    }
    ```
    """
    try:
        tenants, total = m365_tenant_service.get_m365_tenants(db, skip, limit)

        return {
            "total": total,
            "skip": skip,
            "limit": limit,
            "m365_tenants": [M365TenantResponse.model_validate(tenant) for tenant in tenants]
        }

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to retrieve M365 tenants: {str(e)}"
        )


@router.get(
    "/{tenant_id}",
    response_model=M365TenantResponse,
    summary="Get M365 tenant by ID",
    description="Retrieve a single M365 tenant by its unique identifier",
    status_code=status.HTTP_200_OK,
    responses={
        200: {
            "description": "M365 tenant found and returned",
            "model": M365TenantResponse,
        },
        404: {
            "description": "M365 tenant not found",
            "content": {
                "application/json": {
                    "example": {"detail": "M365 tenant with ID 123e4567-e89b-12d3-a456-426614174000 not found"}
                }
            },
        },
    },
)
def get_m365_tenant(
    tenant_id: UUID,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Get a specific M365 tenant by ID.

    - **tenant_id**: UUID of the M365 tenant to retrieve

    Returns the complete M365 tenant details.

    **Example Request:**
    ```
    GET /api/m365-tenants/123e4567-e89b-12d3-a456-426614174000
    Authorization: Bearer <token>
    ```

    **Example Response:**
    ```json
    {
        "id": "123e4567-e89b-12d3-a456-426614174000",
        "client_id": "abc12345-6789-0def-1234-56789abcdef0",
        "tenant_id": "def45678-9abc-0123-4567-89abcdef0123",
        "tenant_name": "dataforth.com",
        "default_domain": "dataforthcorp.onmicrosoft.com",
        "admin_email": "admin@dataforth.com",
        "cipp_name": "Dataforth Corp",
        "notes": "Primary M365 tenant",
        "created_at": "2024-01-15T10:30:00Z",
        "updated_at": "2024-01-15T10:30:00Z"
    }
    ```
    """
    tenant = m365_tenant_service.get_m365_tenant_by_id(db, tenant_id)
    return M365TenantResponse.model_validate(tenant)


@router.get(
    "/by-client/{client_id}",
    response_model=dict,
    summary="Get M365 tenants by client",
    description="Retrieve all M365 tenants for a specific client",
    status_code=status.HTTP_200_OK,
    responses={
        200: {
            "description": "M365 tenants found and returned",
        },
        404: {
            "description": "Client not found",
            "content": {
                "application/json": {
                    "example": {"detail": "Client with ID 123e4567-e89b-12d3-a456-426614174000 not found"}
                }
            },
        },
    },
)
def get_m365_tenants_by_client(
    client_id: UUID,
    skip: int = Query(
        default=0,
        ge=0,
        description="Number of records to skip for pagination"
    ),
    limit: int = Query(
        default=100,
        ge=1,
        le=1000,
        description="Maximum number of records to return (max 1000)"
    ),
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Get all M365 tenants for a specific client.

    - **client_id**: UUID of the client
    - **skip**: Number of M365 tenants to skip (default: 0)
    - **limit**: Maximum number of M365 tenants to return (default: 100, max: 1000)

    Returns a list of M365 tenants for the specified client.

    **Example Request:**
    ```
    GET /api/m365-tenants/by-client/abc12345-6789-0def-1234-56789abcdef0?skip=0&limit=50
    Authorization: Bearer <token>
    ```

    **Example Response:**
    ```json
    {
        "total": 2,
        "skip": 0,
        "limit": 50,
        "client_id": "abc12345-6789-0def-1234-56789abcdef0",
        "m365_tenants": [
            {
                "id": "123e4567-e89b-12d3-a456-426614174000",
                "client_id": "abc12345-6789-0def-1234-56789abcdef0",
                "tenant_id": "def45678-9abc-0123-4567-89abcdef0123",
                "tenant_name": "dataforth.com",
                "default_domain": "dataforthcorp.onmicrosoft.com",
                "admin_email": "admin@dataforth.com",
                "cipp_name": "Dataforth Corp",
                "notes": "Primary M365 tenant",
                "created_at": "2024-01-15T10:30:00Z",
                "updated_at": "2024-01-15T10:30:00Z"
            }
        ]
    }
    ```
    """
    tenants, total = m365_tenant_service.get_m365_tenants_by_client(db, client_id, skip, limit)

    return {
        "total": total,
        "skip": skip,
        "limit": limit,
        "client_id": str(client_id),
        "m365_tenants": [M365TenantResponse.model_validate(tenant) for tenant in tenants]
    }


@router.post(
    "",
    response_model=M365TenantResponse,
    summary="Create new M365 tenant",
    description="Create a new M365 tenant with the provided details",
    status_code=status.HTTP_201_CREATED,
    responses={
        201: {
            "description": "M365 tenant created successfully",
            "model": M365TenantResponse,
        },
        404: {
            "description": "Client not found",
            "content": {
                "application/json": {
                    "example": {"detail": "Client with ID abc12345-6789-0def-1234-56789abcdef0 not found"}
                }
            },
        },
        409: {
            "description": "M365 tenant with tenant_id already exists",
            "content": {
                "application/json": {
                    "example": {"detail": "M365 tenant with tenant_id 'def45678-9abc-0123-4567-89abcdef0123' already exists"}
                }
            },
        },
        422: {
            "description": "Validation error",
            "content": {
                "application/json": {
                    "example": {
                        "detail": [
                            {
                                "loc": ["body", "tenant_id"],
                                "msg": "field required",
                                "type": "value_error.missing"
                            }
                        ]
                    }
                }
            },
        },
    },
)
def create_m365_tenant(
    tenant_data: M365TenantCreate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Create a new M365 tenant.

    Requires a valid JWT token with appropriate permissions.

    **Example Request:**
    ```json
    POST /api/m365-tenants
    Authorization: Bearer <token>
    Content-Type: application/json

    {
        "client_id": "abc12345-6789-0def-1234-56789abcdef0",
        "tenant_id": "def45678-9abc-0123-4567-89abcdef0123",
        "tenant_name": "dataforth.com",
        "default_domain": "dataforthcorp.onmicrosoft.com",
        "admin_email": "admin@dataforth.com",
        "cipp_name": "Dataforth Corp",
        "notes": "Primary M365 tenant"
    }
    ```

    **Example Response:**
    ```json
    {
        "id": "123e4567-e89b-12d3-a456-426614174000",
        "client_id": "abc12345-6789-0def-1234-56789abcdef0",
        "tenant_id": "def45678-9abc-0123-4567-89abcdef0123",
        "tenant_name": "dataforth.com",
        "default_domain": "dataforthcorp.onmicrosoft.com",
        "admin_email": "admin@dataforth.com",
        "cipp_name": "Dataforth Corp",
        "notes": "Primary M365 tenant",
        "created_at": "2024-01-15T10:30:00Z",
        "updated_at": "2024-01-15T10:30:00Z"
    }
    ```
    """
    tenant = m365_tenant_service.create_m365_tenant(db, tenant_data)
    return M365TenantResponse.model_validate(tenant)


@router.put(
    "/{tenant_id}",
    response_model=M365TenantResponse,
    summary="Update M365 tenant",
    description="Update an existing M365 tenant's details",
    status_code=status.HTTP_200_OK,
    responses={
        200: {
            "description": "M365 tenant updated successfully",
            "model": M365TenantResponse,
        },
        404: {
            "description": "M365 tenant or client not found",
            "content": {
                "application/json": {
                    "example": {"detail": "M365 tenant with ID 123e4567-e89b-12d3-a456-426614174000 not found"}
                }
            },
        },
        409: {
            "description": "Conflict with existing M365 tenant",
            "content": {
                "application/json": {
                    "example": {"detail": "M365 tenant with tenant_id 'def45678-9abc-0123-4567-89abcdef0123' already exists"}
                }
            },
        },
    },
)
def update_m365_tenant(
    tenant_id: UUID,
    tenant_data: M365TenantUpdate,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Update an existing M365 tenant.

    - **tenant_id**: UUID of the M365 tenant to update

    Only provided fields will be updated. All fields are optional.

    **Example Request:**
    ```json
    PUT /api/m365-tenants/123e4567-e89b-12d3-a456-426614174000
    Authorization: Bearer <token>
    Content-Type: application/json

    {
        "admin_email": "newadmin@dataforth.com",
        "notes": "Updated administrator contact"
    }
    ```

    **Example Response:**
    ```json
    {
        "id": "123e4567-e89b-12d3-a456-426614174000",
        "client_id": "abc12345-6789-0def-1234-56789abcdef0",
        "tenant_id": "def45678-9abc-0123-4567-89abcdef0123",
        "tenant_name": "dataforth.com",
        "default_domain": "dataforthcorp.onmicrosoft.com",
        "admin_email": "newadmin@dataforth.com",
        "cipp_name": "Dataforth Corp",
        "notes": "Updated administrator contact",
        "created_at": "2024-01-15T10:30:00Z",
        "updated_at": "2024-01-15T14:20:00Z"
    }
    ```
    """
    tenant = m365_tenant_service.update_m365_tenant(db, tenant_id, tenant_data)
    return M365TenantResponse.model_validate(tenant)


@router.delete(
    "/{tenant_id}",
    response_model=dict,
    summary="Delete M365 tenant",
    description="Delete an M365 tenant by its ID",
    status_code=status.HTTP_200_OK,
    responses={
        200: {
            "description": "M365 tenant deleted successfully",
            "content": {
                "application/json": {
                    "example": {
                        "message": "M365 tenant deleted successfully",
                        "tenant_id": "123e4567-e89b-12d3-a456-426614174000"
                    }
                }
            },
        },
        404: {
            "description": "M365 tenant not found",
            "content": {
                "application/json": {
                    "example": {"detail": "M365 tenant with ID 123e4567-e89b-12d3-a456-426614174000 not found"}
                }
            },
        },
    },
)
def delete_m365_tenant(
    tenant_id: UUID,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user),
):
    """
    Delete an M365 tenant.

    - **tenant_id**: UUID of the M365 tenant to delete

    This is a permanent operation and cannot be undone.

    **Example Request:**
    ```
    DELETE /api/m365-tenants/123e4567-e89b-12d3-a456-426614174000
    Authorization: Bearer <token>
    ```

    **Example Response:**
    ```json
    {
        "message": "M365 tenant deleted successfully",
        "tenant_id": "123e4567-e89b-12d3-a456-426614174000"
    }
    ```
    """
    return m365_tenant_service.delete_m365_tenant(db, tenant_id)
