package kz.konturai.parser.controller;

import kz.konturai.parser.config.FacebookLeadProperties;
import kz.konturai.parser.dto.ApiResponse;
import kz.konturai.parser.service.FacebookLeadCollectorService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * Контроллер для ручного запуска скрапинг-парсера Facebook лидов.
 */
@RestController
@RequestMapping("/api/facebook/leads")
@RequiredArgsConstructor
public class FacebookLeadsController {

    private static final Logger log = LoggerFactory.getLogger(FacebookLeadsController.class);

    private final FacebookLeadCollectorService leadCollectorService;
    private final FacebookLeadProperties leadProperties;

    /**
     * Ручной запуск сбора горячих лидов из Facebook.
     *
     * POST /api/facebook/leads/scrape
     */
    @PostMapping("/scrape")
    public ResponseEntity<ApiResponse<Map<String, Object>>> scrapeLeads() {
        log.info("Manual Facebook lead scraping triggered");

        try {
            if (!isConfigured()) {
                return ResponseEntity.badRequest().body(
                        ApiResponse.error("Facebook не настроен: отсутствуют pageId или accessToken")
                );
            }

            int newLeadsCount = leadCollectorService.collectHotLeads();

            Map<String, Object> result = Map.of(
                    "newLeadsCount", newLeadsCount,
                    "pageId", leadProperties.getPageId(),
                    "triggerTime", LocalDateTime.now().toString(),
                    "triggerType", "manual"
            );

            String message = newLeadsCount > 0
                    ? "Сбор лидов завершен. Найдено новых лидов: " + newLeadsCount
                    : "Сбор лидов завершен. Новых лидов не найдено";

            return ResponseEntity.ok(ApiResponse.success(message, result));

        } catch (Exception e) {
            log.error("Manual Facebook lead scraping failed", e);
            return ResponseEntity.internalServerError().body(
                    ApiResponse.error("Ошибка при сборе лидов: " + e.getMessage())
            );
        }
    }

    /**
     * Проверка статуса конфигурации Facebook.
     *
     * GET /api/facebook/leads/status
     */
    @GetMapping("/status")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getStatus() {
        try {
            boolean configured = isConfigured();
            Map<String, Object> status = Map.of(
                    "configured", configured,
                    "pageId", configured ? leadProperties.getPageId() : null,
                    "accessTokenPresent", StringUtils.hasText(leadProperties.getAccessToken()),
                    "cronExpression", leadProperties.getCron(),
                    "graphApiVersion", leadProperties.getGraphApiVersion(),
                    "postsPageSize", leadProperties.getPostsPageSize(),
                    "commentsPageSize", leadProperties.getCommentsPageSize()
            );

            String message = configured
                    ? "Facebook настроен корректно"
                    : "Facebook не настроен: проверьте pageId и accessToken";

            return ResponseEntity.ok(ApiResponse.success(message, status));

        } catch (Exception e) {
            log.error("Failed to get Facebook lead status", e);
            return ResponseEntity.internalServerError().body(
                    ApiResponse.error("Ошибка при получении статуса: " + e.getMessage())
            );
        }
    }

    private boolean isConfigured() {
        return StringUtils.hasText(leadProperties.getPageId())
                && StringUtils.hasText(leadProperties.getAccessToken());
    }
}
