<?php

namespace App\Domain\WhatsApp\Services;

use App\Domain\WhatsApp\Enums\MessageStatus;
use App\Domain\WhatsApp\Enums\MessageType;
use App\Domain\WhatsApp\Models\WhatsAppMessage;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class WhatsAppService
{
    private string $hubUrl;
    private string $hubKey;

    public function __construct()
    {
        $this->hubUrl = rtrim((string) (config('services.messaging_hub.url') ?? ''), '/');
        $this->hubKey = (string) (config('services.messaging_hub.key') ?? '');
    }

    public function sendTemplate(
        string $to,
        string $templateName,
        string $languageCode = 'en_US',
        array $components = [],
        ?int $academyId = null,
        ?int $senderId = null,
    ): WhatsAppMessage {
        $response = $this->sendToHub([
            'phone' => $to,
            'message_type' => 'template',
            'template_name' => $templateName,
            'template_language' => $languageCode,
            'components' => $components,
        ]);

        return $this->logMessage(
            academyId: $academyId,
            to: $to,
            type: MessageType::Template,
            content: $templateName,
            response: $response,
            senderId: $senderId,
        );
    }

    public function sendText(
        string $to,
        string $body,
        ?int $academyId = null,
        ?int $senderId = null,
    ): WhatsAppMessage {
        $response = $this->sendToHub([
            'phone' => $to,
            'message_type' => 'text',
            'content' => $body,
        ]);

        return $this->logMessage(
            academyId: $academyId,
            to: $to,
            type: MessageType::Text,
            content: $body,
            response: $response,
            senderId: $senderId,
        );
    }

    public function sendImage(
        string $to,
        string $imageUrl,
        ?string $caption = null,
        ?int $academyId = null,
        ?int $senderId = null,
    ): WhatsAppMessage {
        $response = $this->sendToHub([
            'phone' => $to,
            'message_type' => 'image',
            'media_url' => $imageUrl,
            'content' => $caption,
        ]);

        return $this->logMessage(
            academyId: $academyId,
            to: $to,
            type: MessageType::Image,
            content: $caption ?? $imageUrl,
            response: $response,
            senderId: $senderId,
        );
    }

    public function sendDocument(
        string $to,
        string $documentUrl,
        ?string $filename = null,
        ?string $caption = null,
        ?int $academyId = null,
        ?int $senderId = null,
    ): WhatsAppMessage {
        $response = $this->sendToHub([
            'phone' => $to,
            'message_type' => 'document',
            'media_url' => $documentUrl,
            'filename' => $filename,
        ]);

        return $this->logMessage(
            academyId: $academyId,
            to: $to,
            type: MessageType::Document,
            content: $caption ?? $filename ?? $documentUrl,
            response: $response,
            senderId: $senderId,
        );
    }

    public function sendBulkText(
        array $recipients,
        string $body,
        ?int $academyId = null,
        ?int $senderId = null,
    ): array {
        $results = ['sent' => 0, 'failed' => 0, 'messages' => []];

        foreach ($recipients as $phone) {
            try {
                $msg = $this->sendText($phone, $body, $academyId, $senderId);
                if ($msg->status === MessageStatus::Failed) {
                    $results['failed']++;
                } else {
                    $results['sent']++;
                }
                $results['messages'][] = $msg;
            } catch (\Throwable $e) {
                $results['failed']++;
                Log::warning("Messaging hub bulk send failed for {$phone}: {$e->getMessage()}");
            }
        }

        return $results;
    }

    public function sendBulkTemplate(
        array $recipients,
        string $templateName,
        string $languageCode = 'en_US',
        array $components = [],
        ?int $academyId = null,
        ?int $senderId = null,
    ): array {
        $results = ['sent' => 0, 'failed' => 0, 'messages' => []];

        foreach ($recipients as $phone) {
            try {
                $msg = $this->sendTemplate($phone, $templateName, $languageCode, $components, $academyId, $senderId);
                if ($msg->status === MessageStatus::Failed) {
                    $results['failed']++;
                } else {
                    $results['sent']++;
                }
                $results['messages'][] = $msg;
            } catch (\Throwable $e) {
                $results['failed']++;
                Log::warning("Messaging hub bulk template failed for {$phone}: {$e->getMessage()}");
            }
        }

        return $results;
    }

    public function isConfigured(): bool
    {
        return !empty($this->hubUrl) && !empty($this->hubKey);
    }

    private function sendToHub(array $data): array
    {
        if (!$this->isConfigured()) {
            return ['success' => false, 'error' => 'Messaging hub not configured'];
        }

        try {
            $response = Http::timeout(30)
                ->withHeaders(['X-Messaging-Key' => $this->hubKey])
                ->post("{$this->hubUrl}/api/messaging/send", $data);

            return $response->json() ?? ['success' => false, 'error' => 'Empty response'];
        } catch (\Throwable $e) {
            Log::error('Messaging hub request failed', ['error' => $e->getMessage()]);
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    private function logMessage(
        ?int $academyId,
        string $to,
        MessageType $type,
        string $content,
        array $response,
        ?int $senderId,
    ): WhatsAppMessage {
        $success = $response['success'] ?? false;
        $status = $success ? MessageStatus::Sent : MessageStatus::Failed;
        $externalId = $response['message_id'] ?? null;
        $errorMessage = $success ? null : ($response['error'] ?? 'Unknown error');

        return WhatsAppMessage::create([
            'academy_id' => $academyId ?? (int) app('current_academy')?->id,
            'wa_message_id' => $externalId,
            'phone_number' => $to,
            'type' => $type->value,
            'content' => mb_substr($content, 0, 2000),
            'status' => $status->value,
            'error_message' => $errorMessage,
            'payload' => $response,
            'response' => $response,
            'sent_by' => $senderId ?? auth()->id(),
            'sent_at' => $success ? now() : null,
        ]);
    }
}
