package com.honey.honey.service;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.honey.honey.config.TelegramProperties;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * Service for interacting with Telegram Bot API.
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TelegramService {

    private final TelegramProperties telegramProperties;
    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * Checks if a user is a member of a Telegram channel/chat.
     * Requires channelCheckerBotToken to be configured.
     * 
     * @param telegramUserId Telegram user ID
     * @param chatId Chat ID (can be channel username like "@honey_channel" or numeric ID)
     * @return true if user is a member (member, administrator, or creator), false otherwise
     * @throws IllegalStateException if channelCheckerBotToken is not configured
     */
    public boolean isUserMemberOfChat(Long telegramUserId, String chatId) {
        String botToken = telegramProperties.getChannelCheckerBotToken();
        if (botToken == null || botToken.isEmpty()) {
            log.error("Channel checker bot token is not configured");
            throw new IllegalStateException("Channel checker bot token is not configured. Please set TELEGRAM_CHANNEL_CHECKER_BOT_TOKEN environment variable or configure it in the mounted secret file.");
        }

        String url = "https://api.telegram.org/bot" + botToken + "/getChatMember";

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("chat_id", chatId)
                .queryParam("user_id", telegramUserId);

        try {
            ResponseEntity<TelegramGetChatMemberResponse> response =
                    restTemplate.getForEntity(
                            builder.toUriString(),
                            TelegramGetChatMemberResponse.class
                    );

            if (response.getBody() == null || !Boolean.TRUE.equals(response.getBody().getOk())) {
                log.warn("getChatMember returned not ok: userId={}, chatId={}", telegramUserId, chatId);
                return false;
            }

            String status = response.getBody().getResult().getStatus();

            return switch (status) {
                case "member", "administrator", "creator" -> true;
                default -> false; // left, kicked, restricted
            };

        } catch (HttpClientErrorException.NotFound e) {
            // user or chat not found
            log.warn("User or chat not found: userId={}, chatId={}", telegramUserId, chatId);
            return false;
        } catch (HttpClientErrorException.BadRequest e) {
            // Check if this is PARTICIPANT_ID_INVALID or "member not found" (user is not a member of the channel)
            String responseBody = e.getResponseBodyAsString();
            if (responseBody != null && (responseBody.contains("PARTICIPANT_ID_INVALID") || 
                    responseBody.contains("member not found"))) {
                return false;
            }
            // Other 400 errors are real problems
            log.error("Bad request when checking chat membership: userId={}, chatId={}, response={}", 
                    telegramUserId, chatId, responseBody);
            throw new IllegalStateException("Telegram API bad request", e);
        } catch (Exception e) {
            // timeout, 5xx, network, etc
            log.error("Error checking chat membership: userId={}, chatId={}", telegramUserId, chatId, e);
            throw new IllegalStateException("Telegram API error", e);
        }
    }

    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class TelegramGetChatMemberResponse {
        @JsonProperty("ok")
        private Boolean ok;

        @JsonProperty("result")
        private ChatMemberResult result;
    }

    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class ChatMemberResult {
        @JsonProperty("status")
        private String status;
    }
}

