<?php

namespace EasyLinkAutomations\HTTP\Controllers\Actions;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;
use EasyLinkAutomations\Models\Connection;

/**
 * Controller for Telegram related API calls.
 * Handles fetching chats for dynamic field loading.
 */
final class TelegramController
{
    private const API_BASE = 'https://api.telegram.org/bot';

    /**
     * Get list of chats the bot has received messages from.
     *
     * Uses getUpdates to discover chats, then deduplicates by chat ID.
     */
    public function chats(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');

        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        $token = Connection::getAccessToken($connectionId);
        if (empty($token)) {
            return Response::error('Invalid connection or token expired', 401);
        }

        $url = self::API_BASE . $token . '/getUpdates?' . http_build_query([
            'limit'  => 100,
            'offset' => 0,
        ]);

        $response = wp_remote_get($url, ['timeout' => 30]);

        if (is_wp_error($response)) {
            return Response::error('Failed to fetch chats: ' . $response->get_error_message());
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);

        if (empty($body['ok'])) {
            return Response::error('Telegram API error: ' . ($body['description'] ?? 'Unknown error'));
        }

        $seen  = [];
        $chats = [];

        foreach ($body['result'] ?? [] as $update) {
            $message = $update['message']
                ?? $update['edited_message']
                ?? $update['channel_post']
                ?? $update['edited_channel_post']
                ?? null;

            if (!$message || empty($message['chat']['id'])) {
                continue;
            }

            $chat   = $message['chat'];
            $chatId = (string) $chat['id'];

            if (isset($seen[$chatId])) {
                continue;
            }
            $seen[$chatId] = true;

            $type  = $chat['type'] ?? 'private';
            $label = match ($type) {
                'group', 'supergroup' => $chat['title'] ?? $chatId,
                'channel'             => $chat['title'] ?? $chatId,
                default               => trim(($chat['first_name'] ?? '') . ' ' . ($chat['last_name'] ?? '')) ?: $chatId,
            };

            $prefix = match ($type) {
                'group', 'supergroup' => '[Group] ',
                'channel'             => '[Channel] ',
                default               => '[Private] ',
            };

            $chats[] = [
                'value' => $chatId,
                'label' => $prefix . $label,
            ];
        }

        usort($chats, fn($a, $b) => strcmp($a['label'], $b['label']));

        return Response::success(['chats' => $chats]);
    }
}
