<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\RateLimiter;

class MailerService
{
    public static function forAutomation(string $type): string
    {
        return match ($type) {
            'event_reminder',
            'birthday_reminder',
            'no_activity_reminder',
            'event_followup',
            'contact_followup',
            'daily_agenda',
            'weekly_overview',
            'daily_summary',
            'free_slots_report' => 'reminder',

            'plan_activated',
            'credits_low',
            'credits_added'    => 'system',

            'aria_composed'    => 'aria',

            'welcome',
            'onboarding'       => 'hello',

            default            => 'smtp',
        };
    }

    public static function channelsForAutomation(string $type): array
    {
        return match ($type) {
            'event_reminder'       => ['push'],
            'daily_agenda'         => ['push', 'email'],
            'weekly_overview'      => ['email'],
            'event_followup'       => ['push'],
            'birthday_reminder'    => ['push'],
            'no_activity_reminder' => ['push'],
            'daily_summary'        => ['email'],
            'contact_followup'     => ['push'],
            'free_slots_report'    => ['email'],
            default                => ['email'],
        };
    }

    public static function pushTextForAutomation(string $type, array $data = []): array
    {
        return match ($type) {
            'event_reminder' => [
                'title' => 'Erinnerung: ' . ($data['title'] ?? 'Termin'),
                'body'  => match (true) {
                    ($data['minutes'] ?? 0) >= 1440 => 'Morgen um ' . ($data['time'] ?? '') . ' Uhr',
                    ($data['minutes'] ?? 0) >= 60   => 'In ' . (($data['minutes'] ?? 60) / 60) . ' Stunde(n)',
                    default                          => 'In ' . ($data['minutes'] ?? 30) . ' Minuten',
                },
            ],
            'daily_agenda' => [
                'title' => 'Deine Agenda — ' . ($data['date'] ?? 'Heute'),
                'body'  => ($data['count'] ?? 0) . ' Termine heute · erster um ' . ($data['first_time'] ?? ''),
            ],
            'birthday_reminder' => [
                'title' => 'Geburtstag: ' . ($data['name'] ?? ''),
                'body'  => ($data['days'] ?? 0) === 0
                    ? 'Heute ist sein/ihr Geburtstag!'
                    : 'In ' . ($data['days'] ?? 1) . ' Tag(en)',
            ],
            'event_followup' => [
                'title' => 'Nachbereitung',
                'body'  => ($data['title'] ?? 'Termin') . ' ist beendet',
            ],
            'no_activity_reminder' => [
                'title' => 'Keine Termine',
                'body'  => 'Du hattest ' . ($data['days'] ?? 3) . ' Tage keine Termine',
            ],
            'contact_followup' => [
                'title' => 'Kontakt-Erinnerung',
                'body'  => ($data['name'] ?? 'Kontakt') . ' seit ' . ($data['days'] ?? 14) . ' Tagen nicht kontaktiert',
            ],
            default => [
                'title' => 'Aziros',
                'body'  => 'Neue Benachrichtigung',
            ],
        };
    }

    public static function sendViaUserSmtp(User $user, string $to, Mailable $mail): bool
    {
        if (!RateLimiter::attempt('user-smtp:' . $user->id, 10, function () {})) {
            \Log::warning('SMTP Rate limit hit', ['user_id' => $user->id]);
            return false;
        }

        $config = $user->smtp_settings ?? [];
        if (empty($config['host'])) {
            return false;
        }

        config(['mail.mailers.user_smtp_' . $user->id => [
            'transport'  => 'smtp',
            'host'       => $config['host'],
            'port'       => $config['port'] ?? 587,
            'encryption' => $config['encryption'] ?? 'tls',
            'username'   => $config['username'],
            'password'   => decrypt($config['password']),
            'from'       => [
                'address' => $config['from_address'] ?? $user->email,
                'name'    => $config['from_name']    ?? $user->name,
            ],
        ]]);

        Mail::mailer('user_smtp_' . $user->id)
            ->to($to)
            ->send($mail);

        $user->emailLogs()->create([
            'to'      => $to,
            'subject' => method_exists($mail, 'envelope') ? $mail->envelope()->subject : 'E-Mail',
            'type'    => 'user_smtp',
        ]);

        return true;
    }
}
