<?php

namespace App\Services\Packages;

use App\Jobs\SendTenantAdminPushNotification;
use App\Models\Tenant;
use App\Models\TenantNotificationLog;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;

class TenantNotificationLogger
{
    public function log(Tenant $tenant, array $attributes): TenantNotificationLog
    {
        $context = Arr::get($attributes, 'context', []);

        $log = $tenant->notificationLogs()->create([
            'type' => $attributes['type'] ?? 'unknown',
            'channel' => $attributes['channel'] ?? 'mail',
            'recipient' => $attributes['recipient'] ?? null,
            'status' => $attributes['status'] ?? 'sent',
            'context' => $context,
            'sent_at' => $attributes['sent_at'] ?? now(),
            'failed_at' => $attributes['failed_at'] ?? null,
            'failure_reason' => $attributes['failure_reason'] ?? null,
        ]);

        Log::info('tenant_notification_log', [
            'tenant_id' => $tenant->id,
            'log_id' => $log->id,
            'type' => $log->type,
            'status' => $log->status,
            'recipient' => $log->recipient,
        ]);

        SendTenantAdminPushNotification::dispatch($log->id);

        return $log;
    }
}
