<?php

namespace App\Services;

use App\Models\User;
use App\Models\UserNotification;
use Illuminate\Support\Collection;

class NotificationService
{
    public function notifyAdmins(
        string $type,
        string $title,
        string $message,
        ?string $actionUrl = null,
        bool $sendEmail = false,
        ?string $emailSubject = null,
        ?string $templateSubjectKey = null,
        ?string $templateBodyKey = null,
        array $templateData = []
    ): array {
        $admins = $this->adminRecipients();
        $report = [];

        foreach ($admins as $admin) {
            $result = $this->notifyUser(
                user: $admin,
                type: $type,
                title: $title,
                message: $message,
                actionUrl: $actionUrl,
                sendEmail: $sendEmail,
                emailSubject: $emailSubject,
                templateSubjectKey: $templateSubjectKey,
                templateBodyKey: $templateBodyKey,
                templateData: $templateData
            );
            $report[] = array_merge(['user_id' => $admin->id, 'email' => $admin->email], $result);
        }

        return $report;
    }

    public function notifyUser(
        User $user,
        string $type,
        string $title,
        string $message,
        ?string $actionUrl = null,
        bool $sendEmail = false,
        ?string $emailSubject = null,
        ?string $templateSubjectKey = null,
        ?string $templateBodyKey = null,
        array $templateData = []
    ): array {
        UserNotification::create([
            'user_id' => $user->id,
            'type' => $type,
            'title' => $title,
            'message' => $message,
            'action_url' => $actionUrl,
            'data' => null,
        ]);

        $emailStatus = 'skipped';
        $emailProvider = null;
        if ($sendEmail && ! empty($user->email)) {
            $data = array_merge([
                'recipient_name' => $user->name,
                'message' => $message,
                'action_url' => (string) ($actionUrl ?? ''),
                'site_name' => (string) config('app.name'),
            ], $templateData);

            if ($templateSubjectKey && $templateBodyKey) {
                $emailResult = app(EmailService::class)->sendTemplatedEmailDetailed(
                    to: (string) $user->email,
                    subjectTemplateKey: $templateSubjectKey,
                    bodyTemplateKey: $templateBodyKey,
                    data: $data,
                    fallbackSubject: $emailSubject ?: $title,
                    fallbackBody: '<p>{{message}}</p><p><a href="{{action_url}}">View</a></p>'
                );
            } else {
                $emailResult = app(EmailService::class)->sendPlainEmailDetailed(
                    to: (string) $user->email,
                    subject: $emailSubject ?: $title,
                    body: $message . ($actionUrl ? "\n\nView: {$actionUrl}" : '')
                );
            }
            $emailStatus = (string) ($emailResult['status'] ?? 'failed');
            $emailProvider = $emailResult['provider'] ?? null;
        }

        return [
            'email_status' => $emailStatus,
            'email_provider' => $emailProvider,
            'email_sent' => $emailStatus === 'sent',
        ];
    }

    private function adminRecipients(): Collection
    {
        return User::query()
            ->where('is_active', true)
            ->whereIn('role', ['owner', 'admin'])
            ->get();
    }
}
