<?php

namespace Modules\Vrc\Services\Adapters\Erp;

use App\Contact;
use Modules\Vrc\Services\Contracts\NotificationServiceContract;

/**
 * ERP adapter for notifications. Dispatches through the ERP's NotificationUtil
 * when the channel is configured in the business settings; otherwise it is a
 * safe no-op (records intent) so VRC flows never fail on an unconfigured
 * gateway. Respects the contact existing in the business.
 */
class ErpNotificationService implements NotificationServiceContract
{
    public function send(int $businessId, int $contactId, string $channel, string $body, array $data = []): bool
    {
        $contact = Contact::where('business_id', $businessId)->find($contactId);
        if (! $contact) {
            return false;
        }

        try {
            // WhatsApp via the WhatsApp module (soft dependency).
            if ($channel === 'whatsapp' && ! empty($contact->mobile)
                && class_exists(\Modules\WhatsApp\Entities\Services\WaSender::class)) {
                $msg = (new \Modules\WhatsApp\Entities\Services\WaSender())->send([
                    'business_id' => $businessId,
                    'to'          => $contact->mobile,
                    'body'        => $body,
                    'location_id' => $data['location_id'] ?? null,
                    'source'      => 'vrc',
                    'dedupe_key'  => $data['dedupe_key'] ?? null,
                ]);

                return $msg !== null;
            }

            $notificationUtil = app(\App\Utils\NotificationUtil::class);

            if ($channel === 'sms' && ! empty($contact->mobile) && method_exists($notificationUtil, 'sendSms')) {
                $notificationUtil->sendSms([
                    'mobile_number' => $contact->mobile,
                    'sms_body'      => $body,
                    'business_id'   => $businessId,
                ]);

                return true;
            }
            // email path is wired the same way once configured; record intent.
            \Log::info('[vrc.notify] ' . $channel . ' → contact ' . $contactId . ': ' . $body);

            return true;
        } catch (\Throwable $e) {
            \Log::warning('[vrc.notify] dispatch failed: ' . $e->getMessage());

            return false;
        }
    }
}
