"""
Pydantic schemas for Accounting model JSONFields.

These schemas validate the JSONFields on accounting-related models:
- QBOSyncLog: webhook_payload

Usage:
    from lightwave.schema.pydantic.models.accounting import (
        QBOWebhookPayloadSchema,
    )
"""

from typing import Any

from pydantic import Field

from lightwave.schema.pydantic.core.base import JSONFieldSchema


class QBOWebhookEntitySchema(JSONFieldSchema):
    """
    Schema for individual entity in QBO webhook notification.

    Example:
        {
            "name": "Invoice",
            "id": "123",
            "operation": "Update",
            "lastUpdated": "2024-01-15T10:30:00.000Z"
        }
    """

    name: str = Field(..., description="Entity type (Invoice, Bill, Customer, etc.)")
    id: str = Field(..., description="QBO entity ID")
    operation: str = Field(..., description="Operation type (Create, Update, Delete, Merge, Void)")
    lastUpdated: str | None = Field(None, description="Last updated timestamp (ISO 8601)")


class QBOWebhookDataChangeSchema(JSONFieldSchema):
    """
    Schema for dataChange in QBO webhook payload.

    Example:
        {
            "entities": [
                {"name": "Invoice", "id": "123", "operation": "Update"}
            ]
        }
    """

    entities: list[dict[str, Any]] = Field(default_factory=list, description="List of changed entities")


class QBOWebhookPayloadSchema(JSONFieldSchema):
    """
    Schema for QBOSyncLog.webhook_payload JSONField.

    Raw QuickBooks Online webhook notification payload.

    Example:
        {
            "eventNotifications": [
                {
                    "realmId": "123456789",
                    "dataChangeEvent": {
                        "entities": [
                            {
                                "name": "Invoice",
                                "id": "123",
                                "operation": "Update",
                                "lastUpdated": "2024-01-15T10:30:00.000Z"
                            }
                        ]
                    }
                }
            ]
        }
    """

    eventNotifications: list[dict[str, Any]] = Field(default_factory=list, description="List of event notifications")

    def get_entities(self) -> list[dict[str, Any]]:
        """Extract all entities from the webhook payload."""
        entities = []
        for notification in self.eventNotifications:
            data_change = notification.get("dataChangeEvent", {})
            entities.extend(data_change.get("entities", []))
        return entities

    def get_realm_ids(self) -> list[str]:
        """Extract all realm IDs from the webhook payload."""
        return [n.get("realmId") for n in self.eventNotifications if n.get("realmId")]
