<?php

declare(strict_types=1);

namespace App\Framework\ErrorAggregation\Alerting;

use App\Framework\ErrorAggregation\AlertUrgency;
use App\Framework\ErrorAggregation\ErrorEvent;
use App\Framework\ErrorAggregation\ErrorPattern;
use App\Framework\Mail\Message;
use App\Framework\Mail\Transport\TransportInterface;

/**
 * Email alert channel implementation
 */
final readonly class EmailAlertChannel implements AlertChannel
{
    private array $lastDeliveryStatus;

    public function __construct(
        private TransportInterface $transport,
        private array $recipients = [],
        private string $fromEmail = 'alerts@example.com',
        private string $fromName = 'Error Alert System'
    ) {
        $this->lastDeliveryStatus = ['status' => 'pending'];
    }

    public function getName(): string
    {
        return 'email';
    }

    public function sendAlert(ErrorPattern $pattern, ErrorEvent $triggeringEvent, array $context = []): bool
    {
        try {
            $subject = $this->buildSubject($pattern, $triggeringEvent);
            $body = $this->buildBody($pattern, $triggeringEvent, $context);

            $message = new Message(
                to: $this->recipients,
                from: $this->fromEmail,
                fromName: $this->fromName,
                subject: $subject,
                body: $body,
                isHtml: true
            );

            $result = $this->transport->send($message);

            $this->lastDeliveryStatus = [
                'status' => $result ? 'sent' : 'failed',
                'timestamp' => date('c'),
                'pattern_id' => $pattern->id->toString(),
                'recipients' => $this->recipients,
            ];

            return $result;

        } catch (\Throwable $e) {
            $this->lastDeliveryStatus = [
                'status' => 'error',
                'timestamp' => date('c'),
                'error' => $e->getMessage(),
                'pattern_id' => $pattern->id->toString(),
            ];

            return false;
        }
    }

    public function canHandle(AlertUrgency $urgency): bool
    {
        // Email can handle all urgency levels
        return true;
    }

    public function getLastDeliveryStatus(): array
    {
        return $this->lastDeliveryStatus;
    }

    public function test(): bool
    {
        try {
            $testMessage = new Message(
                to: $this->recipients,
                from: $this->fromEmail,
                fromName: $this->fromName,
                subject: 'Alert System Test',
                body: 'This is a test message from the error alert system.',
                isHtml: false
            );

            return $this->transport->send($testMessage);
        } catch (\Throwable) {
            return false;
        }
    }

    private function buildSubject(ErrorPattern $pattern, ErrorEvent $triggeringEvent): string
    {
        $urgency = $pattern->getAlertUrgency();
        $urgencyPrefix = match ($urgency) {
            AlertUrgency::URGENT => '[URGENT]',
            AlertUrgency::HIGH => '[HIGH]',
            AlertUrgency::MEDIUM => '[MEDIUM]',
            AlertUrgency::LOW => '[LOW]',
        };

        $subject = "{$urgencyPrefix} Error Alert: {$pattern->service}";

        if ($pattern->isCriticalPattern()) {
            $subject = "[CRITICAL] {$subject}";
        }

        return $subject;
    }

    private function buildBody(ErrorPattern $pattern, ErrorEvent $triggeringEvent, array $context): string
    {
        $urgency = $pattern->getAlertUrgency();
        $urgencyColor = match ($urgency) {
            AlertUrgency::URGENT => '#dc2626',
            AlertUrgency::HIGH => '#ea580c',
            AlertUrgency::MEDIUM => '#ca8a04',
            AlertUrgency::LOW => '#2563eb',
        };

        $html = "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <title>Error Alert</title>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .header { background: {$urgencyColor}; color: white; padding: 20px; border-radius: 5px 5px 0 0; }
                .content { background: #f9f9f9; padding: 20px; border: 1px solid #ddd; border-top: none; }
                .details { background: white; padding: 15px; margin: 10px 0; border-radius: 5px; border-left: 4px solid {$urgencyColor}; }
                .metric { display: inline-block; margin-right: 20px; }
                .metric strong { color: {$urgencyColor}; }
                .footer { background: #333; color: white; padding: 10px; text-align: center; border-radius: 0 0 5px 5px; font-size: 12px; }
                .critical-banner { background: #dc2626; color: white; padding: 10px; text-align: center; font-weight: bold; margin-bottom: 10px; }
            </style>
        </head>
        <body>
        ";

        if ($pattern->isCriticalPattern()) {
            $html .= "<div class='critical-banner'>🚨 CRITICAL PATTERN DETECTED 🚨</div>";
        }

        $html .= "
            <div class='header'>
                <h2>{$pattern->severity->getIcon()} Error Alert - {$pattern->service}</h2>
                <p>Urgency: <strong>{$urgency->value}</strong> | Pattern ID: {$pattern->id->toString()}</p>
            </div>
            
            <div class='content'>
                <div class='details'>
                    <h3>Error Pattern Details</h3>
                    <p><strong>Service:</strong> {$pattern->service}</p>
                    <p><strong>Component:</strong> {$pattern->component}</p>
                    <p><strong>Operation:</strong> {$pattern->operation}</p>
                    <p><strong>Error Code:</strong> {$pattern->errorCode}</p>
                    <p><strong>Message:</strong> {$pattern->normalizedMessage}</p>
                </div>
                
                <div class='details'>
                    <h3>Occurrence Statistics</h3>
                    <div class='metric'><strong>{$pattern->occurrenceCount}</strong> Total Occurrences</div>
                    <div class='metric'><strong>" . number_format($pattern->getFrequency(), 2) . "</strong> Errors/min</div>
                    <div class='metric'><strong>" . count($pattern->affectedUsers) . "</strong> Affected Users</div>
                    <div class='metric'><strong>" . count($pattern->affectedIps) . "</strong> Affected IPs</div>
                </div>
                
                <div class='details'>
                    <h3>Timeline</h3>
                    <p><strong>First Seen:</strong> {$pattern->firstOccurrence->format('Y-m-d H:i:s T')}</p>
                    <p><strong>Last Seen:</strong> {$pattern->lastOccurrence->format('Y-m-d H:i:s T')}</p>
                    <p><strong>Duration:</strong> " . $this->formatDuration($pattern->firstOccurrence, $pattern->lastOccurrence) . "</p>
                </div>
                
                <div class='details'>
                    <h3>Triggering Event</h3>
                    <p><strong>Event ID:</strong> {$triggeringEvent->id->toString()}</p>
                    <p><strong>Request ID:</strong> {$triggeringEvent->requestId}</p>
                    <p><strong>User ID:</strong> " . ($triggeringEvent->userId ?? 'N/A') . "</p>
                    <p><strong>Client IP:</strong> {$triggeringEvent->clientIp}</p>
                    <p><strong>Occurred At:</strong> {$triggeringEvent->occurredAt->format('Y-m-d H:i:s T')}</p>
                </div>
        ";

        if ($triggeringEvent->isSecurityEvent) {
            $html .= "
                <div class='details' style='border-left-color: #dc2626; background-color: #fef2f2;'>
                    <h3>🛡️ Security Event</h3>
                    <p><strong>This is a security-related error that requires immediate attention.</strong></p>
                </div>
            ";
        }

        if (! empty($context['dashboard_url'])) {
            $html .= "
                <div class='details'>
                    <h3>Actions</h3>
                    <p><a href='{$context['dashboard_url']}' style='background: {$urgencyColor}; color: white; padding: 10px 15px; text-decoration: none; border-radius: 3px;'>View in Dashboard</a></p>
                </div>
            ";
        }

        $html .= "
            </div>
            
            <div class='footer'>
                Error Alert System | Pattern Fingerprint: {$pattern->fingerprint}
            </div>
        </body>
        </html>
        ";

        return $html;
    }

    private function formatDuration(\DateTimeImmutable $start, \DateTimeImmutable $end): string
    {
        $diff = $end->getTimestamp() - $start->getTimestamp();

        if ($diff < 60) {
            return "{$diff} seconds";
        } elseif ($diff < 3600) {
            return round($diff / 60) . " minutes";
        } elseif ($diff < 86400) {
            return round($diff / 3600, 1) . " hours";
        } else {
            return round($diff / 86400, 1) . " days";
        }
    }
}
