<?php

namespace App\Jobs\Concerns;

use App\Models\Tenant;
use App\Services\Packages\TenantNotificationLogger;
use Illuminate\Support\Facades\Log;

trait LogsTenantNotifications
{
    protected function notificationLogger(): TenantNotificationLogger
    {
        return app(TenantNotificationLogger::class);
    }

    protected function logNotification(Tenant $tenant, array $attributes): void
    {
        $this->notificationLogger()->log($tenant, $attributes);
    }

    protected function dispatchToRecipients(
        Tenant $tenant,
        iterable $recipients,
        string $type,
        callable $callback,
        array $context = []
    ): void {
        foreach ($recipients as $recipient) {
            try {
                $callback($recipient);

                $this->logNotification($tenant, [
                    'type' => $type,
                    'channel' => 'mail',
                    'recipient' => $recipient,
                    'status' => 'sent',
                    'context' => $context,
                    'sent_at' => now(),
                ]);
            } catch (\Throwable $e) {
                Log::error('Tenant notification failed', [
                    'tenant_id' => $tenant->id,
                    'type' => $type,
                    'recipient' => $recipient,
                    'error' => $e->getMessage(),
                ]);

                $this->logNotification($tenant, [
                    'type' => $type,
                    'channel' => 'mail',
                    'recipient' => $recipient,
                    'status' => 'failed',
                    'context' => $context,
                    'failed_at' => now(),
                    'failure_reason' => $e->getMessage(),
                ]);
            }
        }
    }
}
