<?php

namespace Modules\MedNotify\Services\Channels;

use App\User;
use Modules\MedNotify\Notifications\MedNotifyNotification;

/**
 * In-app channel — writes a Laravel DATABASE notification (the core
 * `notifications` table) that renders in the existing bell dropdown via
 * DataController::parse_notification(). Reuse-first: no new in-app store.
 *
 * Only ERP users have a bell; a 'contact' recipient is skipped for in-app.
 */
class InAppChannel implements ChannelContract
{
    public function send(array $message, array $recipient, array $context): array
    {
        try {
            if (($recipient['type'] ?? null) !== 'user') {
                // Contacts don't own an ERP bell dropdown — nothing to write.
                return ['status' => 'skipped', 'error' => 'in_app is for users only'];
            }

            $user = $recipient['model'] instanceof User
                ? $recipient['model']
                : User::find($recipient['id'] ?? 0);

            if (! $user) {
                return ['status' => 'skipped', 'error' => 'user not found'];
            }

            $user->notify(new MedNotifyNotification([
                'event_key' => $context['event_key'] ?? '',
                'subject'   => $message['subject'] ?? '',
                'body'      => $message['body'] ?? '',
                'link'      => $context['variables']['link'] ?? '',
            ]));

            return ['status' => 'sent', 'error' => null];
        } catch (\Throwable $e) {
            \Log::warning('MedNotify InAppChannel failed: ' . $e->getMessage());

            return ['status' => 'failed', 'error' => $e->getMessage()];
        }
    }
}
