# Copyright (c) 2025 Patrick Motsch
# All rights reserved.
"""
Subscription handler for GraphicalEditor workflow run failures.
Sends email notifications to subscribed users when a workflow run fails.
"""

from typing import List
from modules.datamodels.datamodelMessaging import (
    MessagingEventParameters,
    MessagingSubscriptionExecutionResult,
    MessagingSubscriptionRegistration,
    MessagingChannel,
)


def execute(
    eventParameters: MessagingEventParameters,
    registrations: List[MessagingSubscriptionRegistration],
    messagingService,
) -> MessagingSubscriptionExecutionResult:
    """
    Subscription function for GraphicalEditor run failures.
    Sends email/SMS to registered users when a workflow run fails.
    """
    triggerData = eventParameters.triggerData or {}
    workflowId = triggerData.get("workflowId", "Unknown")
    workflowLabel = triggerData.get("workflowLabel", workflowId)
    runId = triggerData.get("runId", "Unknown")
    error = triggerData.get("error", "Unknown error")
    mandateId = triggerData.get("mandateId", "")

    emailRegistrations = [r for r in registrations if r.channel == MessagingChannel.EMAIL]
    smsRegistrations = [r for r in registrations if r.channel == MessagingChannel.SMS]

    emailSubject = f"Workflow fehlgeschlagen: {workflowLabel}"
    emailMessage = (
        f"Ein Workflow-Run ist fehlgeschlagen.\n\n"
        f"Workflow: {workflowLabel}\n"
        f"Workflow-ID: {workflowId}\n"
        f"Run-ID: {runId}\n"
        f"Fehler: {error}\n\n"
        f"Bitte prüfen Sie den Workflow im Grafischen Editor."
    )

    smsMessage = f"Workflow '{workflowLabel}' fehlgeschlagen: {error[:100]}"

    messagesSent = 0

    for reg in emailRegistrations:
        sendResult = messagingService.sendMessage(
            subject=emailSubject,
            message=emailMessage,
            registration=reg,
        )
        if sendResult.success:
            messagesSent += 1

    for reg in smsRegistrations:
        sendResult = messagingService.sendMessage(
            subject="",
            message=smsMessage,
            registration=reg,
        )
        if sendResult.success:
            messagesSent += 1

    return MessagingSubscriptionExecutionResult(
        success=True,
        messagesSent=messagesSent,
    )
