"""Vessels API endpoints."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any
from uuid import UUID

from vikdata.models.common import PaginatedResponse
from vikdata.models.vessel import (
    Vessel,
    VesselListItem,
    CreateVesselRequest,
    UpdateVesselRequest,
    TransferVesselRequest,
)
from vikdata.models.api_key import (
    ApiKeyResponse,
    ApiKeyCreateResponse,
    ApiKeyCreate,
)

if TYPE_CHECKING:
    from vikdata.client import VikdataClient


class VesselApiKeysAPI:
    """Vessel API key management."""

    def __init__(self, client: "VikdataClient") -> None:
        self._client = client

    async def list(self, vessel_id: UUID) -> list[ApiKeyResponse]:
        """List API keys for a vessel.

        Args:
            vessel_id: Vessel ID

        Returns:
            List of API keys
        """
        return await self._client.request(
            "GET",
            f"/api/v1/vessels/{vessel_id}/api-keys",
            response_model=list[ApiKeyResponse],
        )

    async def create(
        self,
        vessel_id: UUID,
        data: ApiKeyCreate,
    ) -> ApiKeyCreateResponse:
        """Create an API key for a vessel.

        Args:
            vessel_id: Vessel ID
            data: API key creation data

        Returns:
            Created API key with secret (shown only once)
        """
        return await self._client.request(
            "POST",
            f"/api/v1/vessels/{vessel_id}/api-keys",
            json=data,
            response_model=ApiKeyCreateResponse,
        )

    async def revoke(self, vessel_id: UUID, key_id: UUID) -> None:
        """Revoke an API key.

        Args:
            vessel_id: Vessel ID
            key_id: API key ID to revoke
        """
        await self._client.request(
            "DELETE",
            f"/api/v1/vessels/{vessel_id}/api-keys/{key_id}",
        )


class VesselCertificatesAPI:
    """Vessel device certificate management for mTLS authentication."""

    def __init__(self, client: "VikdataClient") -> None:
        self._client = client

    async def list(self, vessel_id: UUID) -> list[dict[str, Any]]:
        """List certificates for a vessel.

        Args:
            vessel_id: Vessel ID

        Returns:
            List of device certificates
        """
        return await self._client.request(
            "GET",
            f"/api/v1/vessels/{vessel_id}/certificates",
        )

    async def register(
        self,
        vessel_id: UUID,
        data: dict[str, Any],
    ) -> dict[str, Any]:
        """Register a new certificate.

        Args:
            vessel_id: Vessel ID
            data: Certificate registration data

        Returns:
            Registered certificate
        """
        return await self._client.request(
            "POST",
            f"/api/v1/vessels/{vessel_id}/certificates",
            json=data,
        )

    async def revoke(
        self,
        vessel_id: UUID,
        cert_id: UUID,
        reason: str | None = None,
    ) -> None:
        """Revoke a certificate.

        Args:
            vessel_id: Vessel ID
            cert_id: Certificate ID to revoke
            reason: Optional revocation reason
        """
        body = {"reason": reason} if reason else None
        await self._client.request(
            "DELETE",
            f"/api/v1/vessels/{vessel_id}/certificates/{cert_id}",
            json=body,
        )


class VesselsAPI:
    """Vessels API endpoints.

    Handles vessel CRUD operations, transfers, API keys, and certificates.
    """

    def __init__(self, client: "VikdataClient") -> None:
        self._client = client
        self.api_keys = VesselApiKeysAPI(client)
        self.certificates = VesselCertificatesAPI(client)

    async def list(
        self,
        *,
        page: int | None = None,
        per_page: int | None = None,
        status: str | None = None,
        vessel_type: str | None = None,
        search: str | None = None,
        sort: str | None = None,
        order: str | None = None,
    ) -> PaginatedResponse[VesselListItem]:
        """List vessels for the current tenant.

        Args:
            page: Page number (default: 1)
            per_page: Items per page (default: 20, max: 100)
            status: Filter by status (from lookup)
            vessel_type: Filter by vessel type (from lookup)
            search: Search by name, IMO, MMSI, or call sign
            sort: Sort field
            order: Sort order ('asc' or 'desc')

        Returns:
            Paginated list of vessels
        """
        params = {
            "page": page,
            "per_page": per_page,
            "status": status,
            "vessel_type": vessel_type,
            "search": search,
            "sort": sort,
            "order": order,
        }
        params = {k: v for k, v in params.items() if v is not None}

        return await self._client.request(
            "GET",
            "/api/v1/vessels",
            params=params,
            response_model=PaginatedResponse[VesselListItem],
        )

    async def get(self, vessel_id: UUID) -> Vessel:
        """Get a vessel by ID.

        Args:
            vessel_id: Vessel ID

        Returns:
            Vessel details
        """
        return await self._client.request(
            "GET",
            f"/api/v1/vessels/{vessel_id}",
            response_model=Vessel,
        )

    async def create(self, data: CreateVesselRequest) -> Vessel:
        """Create a new vessel.

        Args:
            data: Vessel creation data

        Returns:
            Created vessel
        """
        return await self._client.request(
            "POST",
            "/api/v1/vessels",
            json=data,
            response_model=Vessel,
        )

    async def update(
        self,
        vessel_id: UUID,
        data: UpdateVesselRequest,
    ) -> Vessel:
        """Update a vessel.

        Args:
            vessel_id: Vessel ID
            data: Vessel update data

        Returns:
            Updated vessel
        """
        return await self._client.request(
            "PATCH",
            f"/api/v1/vessels/{vessel_id}",
            json=data,
            response_model=Vessel,
        )

    async def delete(self, vessel_id: UUID) -> None:
        """Delete (decommission) a vessel.

        Args:
            vessel_id: Vessel ID
        """
        await self._client.request(
            "DELETE",
            f"/api/v1/vessels/{vessel_id}",
        )

    async def transfer(
        self,
        vessel_id: UUID,
        data: TransferVesselRequest,
    ) -> Vessel:
        """Transfer a vessel to another tenant.

        Args:
            vessel_id: Vessel ID
            data: Transfer request with target tenant

        Returns:
            Updated vessel
        """
        return await self._client.request(
            "POST",
            f"/api/v1/vessels/{vessel_id}/transfer",
            json=data,
            response_model=Vessel,
        )
