<?php

namespace App\Services;

use App\Jobs\SendNotificationJob;
use App\Models\AppNotification;
use App\Models\NotificationTemplate;
use App\Models\User;
use Illuminate\Support\Str;

class NotificationService
{
    public function queueTemplate(string $slug, int $userId, array $data = [], ?string $referenceModule = null, ?int $referenceId = null): void
    {
        $template = NotificationTemplate::where('slug', $slug)->where('is_active', true)->first();
        if (! $template) {
            return;
        }

        $title = $this->interpolate($template->subject ?: $template->name, $data);
        $body = $this->interpolate($template->body, $data);

        SendNotificationJob::dispatch(
            userId: $userId,
            channel: $template->channel,
            title: $title,
            message: $body,
            type: $slug,
            referenceModule: $referenceModule,
            referenceId: $referenceId,
        );
    }

    public function deliver(int $userId, string $channel, string $title, string $message, string $type, ?string $referenceModule = null, ?int $referenceId = null): void
    {
        AppNotification::create([
            'user_id' => $userId,
            'title' => $title,
            'message' => $message,
            'type' => $type,
            'channel' => $channel,
            'reference_module' => $referenceModule,
            'reference_id' => $referenceId,
            'status' => 'sent',
            'scheduled_at' => now(),
            'sent_at' => now(),
        ]);

        // Integration-ready hooks for external channels.
        if ($channel === 'email') {
            // Email provider dispatch hook.
        }

        if ($channel === 'whatsapp') {
            // WhatsApp provider dispatch hook.
        }
    }

    public function queueForUsers(array $userIds, string $channel, string $title, string $message, string $type, ?string $referenceModule = null, ?int $referenceId = null): void
    {
        foreach ($userIds as $userId) {
            SendNotificationJob::dispatch($userId, $channel, $title, $message, $type, $referenceModule, $referenceId);
        }
    }

    private function interpolate(string $text, array $data): string
    {
        foreach ($data as $key => $value) {
            $text = Str::replace('{'.$key.'}', (string) $value, $text);
        }

        return $text;
    }
}
