<?php

namespace App\Services;

use App\Models\Setting;
use App\Models\Ticket;
use App\Models\TicketDepartment;
use App\Models\TicketReply;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class TicketTelegramService
{
    private string $baseUrl = 'https://api.telegram.org/bot';

    public function isEnabled(TicketDepartment $department): bool
    {
        return $department->telegram_enabled
            && !empty($department->telegram_chat_id)
            && !empty($this->getBotToken());
    }

    private function getBotToken(): string
    {
        return Setting::get('telegram_bot_token', config('ticket-integrations.telegram.bot_token', ''));
    }

    /**
     * Send ticket opened notification to Telegram group.
     */
    public function sendTicketOpened(Ticket $ticket): void
    {
        $department = $ticket->department;
        if (!$this->isEnabled($department)) {
            return;
        }

        $client = $ticket->client;
        $clientName = $client ? ($client->first_name . ' ' . $client->last_name) : 'Guest';
        $firstMessage = $ticket->replies()->oldest()->first()?->message ?? '';

        $text = "🎫 *New Ticket #{$ticket->id}*\n\n"
            . "*Subject:* {$this->escape($ticket->title)}\n"
            . "*Priority:* " . ucfirst($ticket->priority) . "\n"
            . "*Client:* {$this->escape($clientName)} ({$ticket->mail})\n"
            . "*Department:* " . $this->escape($department->name ?? '-') . "\n\n"
            . $this->escape(\Str::limit($firstMessage, 500));

        try {
            $result = $this->sendMessage($department->telegram_chat_id, $text);
            if ($result && isset($result['result']['message_id'])) {
                $ticket->update(['telegram_message_id' => $result['result']['message_id']]);
            }
        } catch (\Exception $e) {
            Log::error('Telegram ticket opened error', ['ticket' => $ticket->id, 'error' => $e->getMessage()]);
        }
    }

    /**
     * Send reply notification to Telegram group.
     */
    public function sendReply(Ticket $ticket, TicketReply $reply): void
    {
        $department = $ticket->department;
        if (!$this->isEnabled($department) || $reply->is_internal) {
            return;
        }

        $authorName = $reply->isFromAdmin()
            ? ($reply->admin?->name ?? 'Admin')
            : ($reply->client?->first_name . ' ' . $reply->client?->last_name);

        $label = $reply->isFromAdmin() ? '👤 Staff Reply' : '💬 Client Reply';

        $text = "{$label} on *Ticket #{$ticket->id}*\n"
            . "*By:* {$this->escape($authorName)}\n\n"
            . $this->escape(\Str::limit($reply->message, 500));

        try {
            // Reply to original message if available
            $replyTo = $ticket->telegram_message_id ? (int) $ticket->telegram_message_id : null;
            $this->sendMessage($department->telegram_chat_id, $text, $replyTo);
        } catch (\Exception $e) {
            Log::error('Telegram reply error', ['ticket' => $ticket->id, 'error' => $e->getMessage()]);
        }
    }

    /**
     * Send escalation notice to Telegram group.
     */
    public function sendEscalationNotice(Ticket $ticket, string $ruleName, array $changes): void
    {
        $department = $ticket->department;
        if (!$this->isEnabled($department)) {
            return;
        }

        $parts = ["🚨 *Ticket #{$ticket->id} Escalated*\n*Rule:* {$this->escape($ruleName)}"];

        if (isset($changes['department_id'])) {
            $parts[] = "• Department changed";
        }
        if (isset($changes['status_id'])) {
            $parts[] = "��� Status changed";
        }
        if (isset($changes['priority'])) {
            $parts[] = "• Priority: {$changes['priority']['from']} → {$changes['priority']['to']}";
        }
        if (isset($changes['flagged'])) {
            $parts[] = "• Flagged to admin";
        }
        if (isset($changes['auto_reply'])) {
            $parts[] = "• Auto\-reply sent";
        }

        $text = implode("\n", $parts);

        try {
            $replyTo = $ticket->telegram_message_id ? (int) $ticket->telegram_message_id : null;
            $this->sendMessage($department->telegram_chat_id, $text, $replyTo);
        } catch (\Exception $e) {
            Log::error('Telegram escalation notice error', ['ticket' => $ticket->id, 'error' => $e->getMessage()]);
        }
    }

    /**
     * Send ticket closed notification.
     */
    public function sendTicketClosed(Ticket $ticket): void
    {
        $department = $ticket->department;
        if (!$this->isEnabled($department)) {
            return;
        }

        $text = "✅ *Ticket #{$ticket->id} Closed*\n"
            . "*Subject:* {$this->escape($ticket->title)}";

        try {
            $replyTo = $ticket->telegram_message_id ? (int) $ticket->telegram_message_id : null;
            $this->sendMessage($department->telegram_chat_id, $text, $replyTo);
        } catch (\Exception $e) {
            Log::error('Telegram ticket closed error', ['ticket' => $ticket->id, 'error' => $e->getMessage()]);
        }
    }

    private function sendMessage(string $chatId, string $text, ?int $replyToMessageId = null): ?array
    {
        $params = [
            'chat_id' => $chatId,
            'text' => $text,
            'parse_mode' => 'Markdown',
            'disable_web_page_preview' => true,
        ];

        if ($replyToMessageId) {
            $params['reply_to_message_id'] = $replyToMessageId;
        }

        $response = Http::post("{$this->baseUrl}{$this->getBotToken()}/sendMessage", $params);

        return $response->json();
    }

    private function escape(string $text): string
    {
        return str_replace(['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!'], ['\_', '\*', '\[', '\]', '\(', '\)', '\~', '\`', '\>', '\#', '\+', '\-', '\=', '\|', '\{', '\}', '\.', '\!'], $text);
    }
}
