<?php
if (!defined('ABSPATH'))
    exit;

class Dori_Chatbot_Crawler_Service
{
    public static function start_crawl($user_id)
    {
        $api_url = Dori_Chatbot_API_Constants::get_crawler_base_url() . Dori_Chatbot_API_Constants::ENDPOINT_ADD_SELLER_ACCOUNT . "/" . $user_id;

        $data = array(
            'site_url' => get_site_url()
        );

        $response = Dori_Chatbot_API_Client::call_api_simple($api_url, $data);

        if (is_wp_error($response)) {
            throw new Exception('Failed to start crawling: ' . $response->get_error_message());
        }

        $response_code = wp_remote_retrieve_response_code($response);

        if ($response_code !== 200) {
            $response_body = wp_remote_retrieve_body($response);
            throw new Exception('Server error: ' . $response_body);
        }

        return true;
    }

    public static function get_crawl_status($user_id)
    {
        $api_url = Dori_Chatbot_API_Constants::get_crawler_base_url() . Dori_Chatbot_API_Constants::ENDPOINT_CRAWL_PROGRESS . "/" . $user_id;

        $response = Dori_Chatbot_API_Client::call_api_get($api_url);

        if (is_wp_error($response)) {
            throw new Exception('Failed to get crawl status: ' . $response->get_error_message());
        }

        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            $response_body = wp_remote_retrieve_body($response);
            throw new Exception('Server error: ' . $response_body);
        }

        $response_body = wp_remote_retrieve_body($response);
        $status_data = json_decode($response_body, true);

        return $status_data;
    }

    public static function get_wc_product_count()
    {
        if (!class_exists('WooCommerce')) {
            return 0;
        }

        $count = Dori_Chatbot_Cache_Manager::get_product_count();

        return $count;
    }
}
