<?php

namespace App\Services\Notifications;

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

class HttpReminderProvider implements ReminderChannelProvider
{
    public function __construct(private string $channel) {}

    public function send(ReminderNotificationLog $log, Customer $customer): NotificationDeliveryResult
    {
        $endpoint=(string)config("reminders.providers.{$this->channel}.endpoint",'');
        $token=(string)config("reminders.providers.{$this->channel}.token",'');
        $timeout=(int)config("reminders.providers.{$this->channel}.timeout",15);

        if(blank($endpoint)) return NotificationDeliveryResult::failed(strtoupper($this->channel).' 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('Provider returned HTTP '.$response->status().'.',$body);
            return NotificationDeliveryResult::delivered($body !== '' ? $body : json_encode(['status'=>$response->status()]));
        } catch(Throwable $e) {
            return NotificationDeliveryResult::failed($e->getMessage());
        }
    }
}
