<?php

namespace App\Services;

use App\Models\MailQueue;

class MailService
{
    public static function queue($to, $template, $meta = [], $locale = 'de', $subject = null, $userId = null)
    {
        // 🔥 dedup für verify
        if ($template === 'auth.verify' && $userId) {
            MailQueue::where('user_id', $userId)
                ->where('template', 'auth.verify')
                ->whereIn('status', ['pending', 'processing'])
                ->update([
                    'status' => 'canceled'
                ]);
        }

        MailQueue::create([
            'user_id' => $userId,
            'to' => $to,
            'subject' => $subject ?? self::resolveSubject($template, $locale),
            'template' => $template,
            'meta' => $meta,
            'locale' => $locale,
            'available_at' => now(),
            'status' => 'pending',
        ]);

    }

    protected static function resolveSubject($template, $locale)
    {
        return match ($template) {
            'auth.verify' => t('mail.auth.verify.subject', [], $locale),
            default => 'Notification',
        };
    }

}
