<?php

namespace App\Services\Notifications;

use App\Models\Business;
use App\Models\Customer;
use App\Models\ReminderNotificationLog;
use Illuminate\Support\Facades\Http;
use Throwable;

class WhatsAppReminderProvider implements ReminderChannelProvider
{
    public function send(ReminderNotificationLog $log, Customer $customer): NotificationDeliveryResult
    {
        $business = $log->business ?: Business::query()->find($log->business_id);
        $endpoint = trim((string) ($business?->whatsapp_api_endpoint ?: config('reminders.providers.whatsapp.endpoint', '')));
        $token = (string) ($business?->whatsapp_api_token ?: config('reminders.providers.whatsapp.token', ''));
        $timeout = (int) config('reminders.providers.whatsapp.timeout', 15);

        if ($endpoint === '') {
            return NotificationDeliveryResult::failed('WhatsApp provider is not configured.');
        }

        try {
            $request = Http::acceptJson()->timeout(max(1, $timeout));
            if (filled($token)) {
                $request = $request->withToken($token);
            }

            $response = $request->post($endpoint, [
                'to' => $log->recipient,
                'message' => $log->message,
                'subject' => $log->subject,
                'reference' => $log->idempotency_key,
                'customer_id' => $log->customer_id,
                'loan_id' => $log->loan_id,
                'installment_id' => $log->loan_installment_id,
                'reminder_type' => $log->reminder_type,
            ]);

            $body = mb_substr((string) $response->body(), 0, 12000);
            if (! $response->successful()) {
                return NotificationDeliveryResult::failed('WhatsApp provider returned HTTP '.$response->status().'.', $body);
            }

            return NotificationDeliveryResult::delivered($body !== '' ? $body : json_encode(['status' => $response->status()]));
        } catch (Throwable $e) {
            return NotificationDeliveryResult::failed($e->getMessage());
        }
    }
}
