# Copyright (c) 2025 Patrick Motsch
# All rights reserved.
"""Messaging models: MessagingSubscription, MessagingSubscriptionRegistration, MessagingDelivery."""

import uuid
from typing import Optional
from enum import Enum
from pydantic import BaseModel, Field, ConfigDict
from modules.datamodels.datamodelBase import PowerOnModel
from modules.shared.i18nRegistry import i18nModel


class MessagingChannel(str, Enum):
    """Messaging channel types"""
    EMAIL = "email"
    SMS = "sms"
    WHATSAPP = "whatsapp"
    TEAMS_CHAT = "teams_chat"
    # Weitere Kanäle können hier hinzugefügt werden


class DeliveryStatus(str, Enum):
    """Individual delivery status"""
    PENDING = "pending"
    SENT = "sent"
    FAILED = "failed"


@i18nModel("Messaging-Abonnement")
class MessagingSubscription(PowerOnModel):
    """Data model for messaging subscriptions"""
    id: str = Field(
        default_factory=lambda: str(uuid.uuid4()),
        description="Unique ID of the subscription",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "ID",
        },
    )
    subscriptionId: str = Field(
        description="Unique subscription identifier (e.g., 'system_errors', 'audit_login')",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": False,
            "frontend_required": True,
            "label": "Abonnement-ID",
        },
    )
    subscriptionLabel: str = Field(
        description="Display name of the subscription",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": False,
            "frontend_required": True,
            "label": "Bezeichnung",
        },
    )
    mandateId: str = Field(
        description="ID of the mandate this subscription belongs to",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Mandanten-ID",
        },
    )
    featureInstanceId: str = Field(
        description="ID of the feature instance this subscription belongs to",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Feature-Instanz-ID",
        },
    )
    description: Optional[str] = Field(
        default=None,
        description="Description of the subscription",
        json_schema_extra={
            "frontend_type": "textarea",
            "frontend_readonly": False,
            "frontend_required": False,
            "label": "Beschreibung",
        },
    )
    isSystemSubscription: bool = Field(
        default=False,
        description="Whether this is a system subscription (only admin can create)",
        json_schema_extra={
            "frontend_type": "checkbox",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "System-Abonnement",
        },
    )
    enabled: bool = Field(
        default=True,
        description="Whether the subscription is enabled",
        json_schema_extra={
            "frontend_type": "checkbox",
            "frontend_readonly": False,
            "frontend_required": False,
            "label": "Aktiviert",
        },
    )

    model_config = ConfigDict(use_enum_values=True)


@i18nModel("Messaging-Registrierung")
class MessagingSubscriptionRegistration(BaseModel):
    """Data model for user registrations to messaging subscriptions"""
    id: str = Field(
        default_factory=lambda: str(uuid.uuid4()),
        description="Unique ID of the registration",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "ID",
        },
    )
    mandateId: str = Field(
        description="ID of the mandate this registration belongs to",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Mandanten-ID",
        },
    )
    featureInstanceId: str = Field(
        description="ID of the feature instance this registration belongs to",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Feature-Instanz-ID",
        },
    )
    subscriptionId: str = Field(
        description="ID of the subscription this registration belongs to",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": False,
            "frontend_required": True,
            "label": "Abonnement-ID",
        },
    )
    userId: str = Field(
        description="ID of the user registered to this subscription",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Benutzer-ID",
        },
    )
    channel: MessagingChannel = Field(
        description="Channel type for this registration",
        json_schema_extra={
            "frontend_type": "select",
            "frontend_readonly": False,
            "frontend_required": True,
            "frontend_options": [
                {"value": "email", "label": "Email"},
                {"value": "sms", "label": "SMS"},
                {"value": "whatsapp", "label": "WhatsApp"},
                {"value": "teams_chat", "label": "Teams Chat"},
            ],
            "label": "Kanal",
        },
    )
    channelConfig: str = Field(
        default="",
        description="Channel-specific configuration (e.g., email address, phone number, Teams user ID)",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": False,
            "frontend_required": False,
            "label": "Kanal-Konfiguration",
        },
    )
    enabled: bool = Field(
        default=True,
        description="Whether this registration is enabled",
        json_schema_extra={
            "frontend_type": "checkbox",
            "frontend_readonly": False,
            "frontend_required": False,
            "label": "Aktiviert",
        },
    )

    model_config = ConfigDict(use_enum_values=True)


@i18nModel("Messaging-Zustellung")
class MessagingDelivery(BaseModel):
    """Data model for individual message deliveries"""
    id: str = Field(
        default_factory=lambda: str(uuid.uuid4()),
        description="Unique ID of the delivery",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "ID",
        },
    )
    mandateId: str = Field(
        description="ID of the mandate this delivery belongs to",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Mandanten-ID",
        },
    )
    featureInstanceId: str = Field(
        description="ID of the feature instance this delivery belongs to",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Feature-Instanz-ID",
        },
    )
    subscriptionId: str = Field(
        description="ID of the subscription this delivery belongs to",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Abonnement-ID",
        },
    )
    userId: str = Field(
        description="ID of the user receiving this delivery",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Benutzer-ID",
        },
    )
    channel: MessagingChannel = Field(
        description="Channel used for this delivery",
        json_schema_extra={
            "frontend_type": "select",
            "frontend_readonly": True,
            "frontend_required": False,
            "frontend_options": [
                {"value": "email", "label": "Email"},
                {"value": "sms", "label": "SMS"},
                {"value": "whatsapp", "label": "WhatsApp"},
                {"value": "teams_chat", "label": "Teams Chat"},
            ],
            "label": "Kanal",
        },
    )
    status: DeliveryStatus = Field(
        default=DeliveryStatus.PENDING,
        description="Status of the delivery",
        json_schema_extra={
            "frontend_type": "select",
            "frontend_readonly": True,
            "frontend_required": False,
            "frontend_options": [
                {"value": "pending", "label": "Pending"},
                {"value": "sent", "label": "Sent"},
                {"value": "failed", "label": "Failed"},
            ],
            "label": "Status",
        },
    )
    errorMessage: Optional[str] = Field(
        default=None,
        description="Error message if delivery failed",
        json_schema_extra={
            "frontend_type": "textarea",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Fehlermeldung",
        },
    )
    sentAt: Optional[float] = Field(
        default=None,
        description="When the delivery was sent (UTC timestamp in seconds)",
        json_schema_extra={
            "frontend_type": "datetime",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Gesendet am",
        },
    )

    model_config = ConfigDict(use_enum_values=True)


@i18nModel("Messaging-Ereignisparameter")
class MessagingEventParameters(BaseModel):
    """Data model for event parameters passed to subscription functions"""
    triggerData: dict = Field(
        default_factory=dict,
        description="Event data from trigger as dictionary/JSON",
        json_schema_extra={
            "frontend_type": "json",
            "frontend_readonly": False,
            "frontend_required": False,
            "label": "Trigger-Daten",
        },
    )


@i18nModel("Messaging-Sendeergebnis")
class MessagingSendResult(BaseModel):
    """Data model for sendMessage result"""
    success: bool = Field(
        description="Whether the message was sent successfully",
        json_schema_extra={
            "frontend_type": "checkbox",
            "frontend_readonly": True,
            "frontend_required": True,
            "label": "Erfolg",
        },
    )
    deliveryId: Optional[str] = Field(
        default=None,
        description="ID of the created MessagingDelivery record",
        json_schema_extra={
            "frontend_type": "text",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Zustellungs-ID",
        },
    )
    errorMessage: Optional[str] = Field(
        default=None,
        description="Error message if sending failed",
        json_schema_extra={
            "frontend_type": "textarea",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Fehlermeldung",
        },
    )


@i18nModel("Messaging-Abonnement-Ausführung")
class MessagingSubscriptionExecutionResult(BaseModel):
    """Data model for subscription function execution result"""
    success: bool = Field(
        description="Whether the subscription execution was successful",
        json_schema_extra={
            "frontend_type": "checkbox",
            "frontend_readonly": True,
            "frontend_required": True,
            "label": "Erfolg",
        },
    )
    messagesSent: int = Field(
        default=0,
        description="Number of messages sent",
        json_schema_extra={
            "frontend_type": "number",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Gesendete Nachrichten",
        },
    )
    errorMessage: Optional[str] = Field(
        default=None,
        description="Error message if execution failed",
        json_schema_extra={
            "frontend_type": "textarea",
            "frontend_readonly": True,
            "frontend_required": False,
            "label": "Fehlermeldung",
        },
    )
