"""In-memory webhook repository implementation."""

from __future__ import annotations

from collections.abc import Sequence
from typing import TYPE_CHECKING
from uuid import UUID

if TYPE_CHECKING:
    from noteflow.domain.webhooks import WebhookConfig, WebhookDelivery


class InMemoryWebhookRepository:
    """In-memory webhook repository for testing.

    Provide a functional webhook repository backed by dictionaries
    for use in tests and memory mode.
    """

    def __init__(self) -> None:
        """Initialize with empty storage."""
        self._configs: dict[UUID, WebhookConfig] = {}
        self._deliveries: dict[UUID, list[WebhookDelivery]] = {}

    async def get_all_enabled(
        self,
        workspace_id: UUID | None = None,
    ) -> Sequence[WebhookConfig]:
        """Retrieve all enabled webhook configurations (in-memory)."""
        configs = [c for c in self._configs.values() if c.enabled]
        if workspace_id is not None:
            configs = [c for c in configs if c.workspace_id == workspace_id]
        return sorted(configs, key=lambda c: c.created_at, reverse=True)

    async def get_all(
        self,
        workspace_id: UUID | None = None,
    ) -> Sequence[WebhookConfig]:
        """Retrieve all webhook configurations regardless of enabled status."""
        configs = list(self._configs.values())
        if workspace_id is not None:
            configs = [c for c in configs if c.workspace_id == workspace_id]
        return sorted(configs, key=lambda c: c.created_at, reverse=True)

    async def get_by_id(self, webhook_id: UUID) -> WebhookConfig | None:
        """Retrieve a webhook configuration by ID.

        Args:
            webhook_id: Unique webhook identifier.

        Returns:
            Webhook configuration or None if not found.
        """
        return self._configs.get(webhook_id)

    async def create(self, config: WebhookConfig) -> WebhookConfig:
        """Persist a new webhook configuration.

        Args:
            config: Webhook configuration to create.

        Returns:
            Created webhook.
        """
        self._configs[config.id] = config
        return config

    async def update(self, config: WebhookConfig) -> WebhookConfig:
        """Update an existing webhook configuration.

        Args:
            config: Webhook configuration with updated values.

        Returns:
            Updated webhook configuration.

        Raises:
            ValueError: If webhook does not exist.
        """
        if config.id not in self._configs:
            msg = f"Webhook {config.id} not found"
            raise ValueError(msg)
        self._configs[config.id] = config
        return config

    async def delete(self, webhook_id: UUID) -> bool:
        """Delete a webhook configuration.

        Args:
            webhook_id: Unique webhook identifier.

        Returns:
            True if deleted, False if not found.
        """
        if webhook_id not in self._configs:
            return False
        del self._configs[webhook_id]
        self._deliveries.pop(webhook_id, None)
        return True

    async def add_delivery(self, delivery: WebhookDelivery) -> WebhookDelivery:
        """Record a webhook delivery attempt.

        Args:
            delivery: Delivery record to persist.

        Returns:
            Persisted delivery record.
        """
        if delivery.webhook_id not in self._deliveries:
            self._deliveries[delivery.webhook_id] = []
        self._deliveries[delivery.webhook_id].insert(0, delivery)
        return delivery

    async def get_deliveries(
        self,
        webhook_id: UUID,
        limit: int = 50,
    ) -> Sequence[WebhookDelivery]:
        """Retrieve delivery history for a webhook (in-memory)."""
        deliveries = self._deliveries.get(webhook_id, [])
        return deliveries[:limit]
