<?php

namespace App\Services\Providers;

use App\Models\Appointment;
use Illuminate\Support\Facades\Http;
use RuntimeException;

class WhatsAppProvider
{
    public function sendAppointmentReminder(string $phone, Appointment $appointment): ?string
    {
        $config = config('clinic.whatsapp');

        if (! ($config['enabled'] ?? false)) {
            throw new RuntimeException('WhatsApp provider is disabled.');
        }

        if (empty($config['phone_number_id']) || empty($config['access_token'])) {
            throw new RuntimeException('WhatsApp provider credentials are not configured.');
        }

        $url = rtrim($config['base_url'], '/').'/'.$config['version'].'/'.$config['phone_number_id'].'/messages';

        $response = Http::withToken($config['access_token'])
            ->timeout(20)
            ->acceptJson()
            ->post($url, [
                'messaging_product' => 'whatsapp',
                'to' => ltrim($phone, '+'),
                'type' => 'template',
                'template' => [
                    'name' => $config['template'],
                    'language' => ['code' => $config['language']],
                    'components' => [
                        [
                            'type' => 'body',
                            'parameters' => [
                                ['type' => 'text', 'text' => $appointment->patient?->name ?? 'Patient'],
                                ['type' => 'text', 'text' => $appointment->appointment_code],
                                ['type' => 'text', 'text' => $appointment->scheduled_start_at?->toDateTimeString()],
                            ],
                        ],
                    ],
                ],
            ])
            ->throw()
            ->json();

        return $response['messages'][0]['id'] ?? null;
    }
}
