<?php

namespace App\Services\Messaging;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class WhatsAppService
{
    public function sendTemplate(string $mobile, ?string $template, array $data = []): bool
    {
        $baseUrl = rtrim((string) config('lead.whatsapp.api_base_url'), '/');
        $payload = [
            'vendor_uid' => (string) config('lead.whatsapp.vendor_uid'),
            'phone_number_id' => (string) config('lead.whatsapp.phone_number_id'),
            'to' => $mobile,
            'template' => $template,
            'parameters' => $data,
        ];
        Log::info('Kiyowap request prepared.', [
            'url' => $baseUrl . '/messages',
            'mobile' => $this->maskMobile($mobile),
            'payload' => $this->sanitizePayload($payload),
        ]);

        if (! config('lead.whatsapp.enabled')) {
            Log::info('WhatsApp disabled, skipping message.', ['mobile' => $mobile, 'template' => $template]);
            return false;
        }

        $accessToken = (string) config('lead.whatsapp.access_token');
        $vendorUid = (string) config('lead.whatsapp.vendor_uid');
        $phoneNumberId = (string) config('lead.whatsapp.phone_number_id');

        if ($baseUrl === '' || $accessToken === '' || $vendorUid === '' || $phoneNumberId === '') {
            Log::warning('Kiyowap config missing, skipping WhatsApp message.', [
                'mobile' => $mobile,
                'template' => $template,
            ]);
            return false;
        }

        try {
            $response = Http::withToken($accessToken)
                ->acceptJson()
                ->post($baseUrl . '/messages', $payload);

            if (! $response->successful()) {
                Log::error('Kiyowap API request failed.', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                    'mobile' => $this->maskMobile($mobile),
                    'template' => $template,
                    'url' => $baseUrl . '/messages',
                    'payload' => $this->sanitizePayload($payload),
                ]);
                return false;
            }

            Log::info('Kiyowap API request succeeded.', [
                'status' => $response->status(),
                'body' => $response->body(),
                'mobile' => $this->maskMobile($mobile),
                'template' => $template,
            ]);

            return true;
        } catch (\Throwable $exception) {
            report($exception);
            return false;
        }
    }

    private function maskMobile(string $mobile): string
    {
        if (strlen($mobile) <= 4) {
            return str_repeat('*', strlen($mobile));
        }
        return str_repeat('*', max(strlen($mobile) - 4, 0)) . substr($mobile, -4);
    }

    private function sanitizePayload(array $payload): array
    {
        $payload['to'] = $this->maskMobile((string) ($payload['to'] ?? ''));
        return $payload;
    }
}
