package cms

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"time"

	"bitbucket.org/imediabrands/oos-service/internal/cache"
)

type Service struct {
	baseURL    string
	apiKey     string
	httpClient *http.Client
	cache      *cache.Cache
}

func NewService(baseURL, apiKey string, cacheTTL time.Duration) *Service {
	return &Service{
		baseURL: baseURL,
		apiKey:  apiKey,
		httpClient: &http.Client{
			Timeout: 30 * time.Second,
		},
		cache: cache.New(cacheTTL),
	}
}

func (s *Service) GetCategories() ([]byte, error) {
	cacheKey := "categories"

	if data, found := s.cache.Get(cacheKey); found {
		log.Printf("[CACHE HIT] %s", cacheKey)
		return data, nil
	}

	log.Printf("[CACHE MISS] %s - fetching from API", cacheKey)
	data, err := s.fetchFromAPI("getcategories", nil)
	if err != nil {
		return nil, err
	}

	s.cache.Set(cacheKey, data)
	return data, nil
}

func (s *Service) GetCategoryArticles(catID string) ([]byte, error) {
	cacheKey := fmt.Sprintf("category_articles:%s", catID)

	if data, found := s.cache.Get(cacheKey); found {
		log.Printf("[CACHE HIT] %s", cacheKey)
		return data, nil
	}

	log.Printf("[CACHE MISS] %s - fetching from API", cacheKey)
	params := url.Values{
		"cat_id": []string{catID},
	}
	data, err := s.fetchFromAPI("getcategoryarticles", params)
	if err != nil {
		return nil, err
	}

	s.cache.Set(cacheKey, data)
	return data, nil
}

// GetSubcategoryArticles fetches articles filtered by both a parent category
// and a subcategory, sending cat_id + subcat_id to the CMS API.
func (s *Service) GetSubcategoryArticles(catID, subcatID string) ([]byte, error) {
	cacheKey := fmt.Sprintf("category_articles:%s:%s", catID, subcatID)

	if data, found := s.cache.Get(cacheKey); found {
		log.Printf("[CACHE HIT] %s", cacheKey)
		return data, nil
	}

	log.Printf("[CACHE MISS] %s - fetching from API", cacheKey)
	params := url.Values{
		"cat_id":    []string{catID},
		"subcat_id": []string{subcatID},
	}
	data, err := s.fetchFromAPI("getcategoryarticles", params)
	if err != nil {
		return nil, err
	}

	s.cache.Set(cacheKey, data)
	return data, nil
}

func (s *Service) GetArticle(articleID string) ([]byte, error) {
	cacheKey := fmt.Sprintf("article:%s", articleID)

	if data, found := s.cache.Get(cacheKey); found {
		log.Printf("[CACHE HIT] %s", cacheKey)
		return data, nil
	}

	log.Printf("[CACHE MISS] %s - fetching from API", cacheKey)
	params := url.Values{
		"id": []string{articleID},
	}
	data, err := s.fetchFromAPI("getarticledata", params)
	if err != nil {
		return nil, err
	}

	s.cache.Set(cacheKey, data)
	return data, nil
}

// RefreshCategories re-fetches the categories and replaces the cached copy, so
// requests keep hitting the cache. On failure the cached copy stays as it is.
func (s *Service) RefreshCategories() ([]byte, error) {
	return s.refresh("categories", "getcategories", nil)
}

// RefreshCategoryArticles does the same for GetCategoryArticles.
func (s *Service) RefreshCategoryArticles(catID string) ([]byte, error) {
	return s.refresh(fmt.Sprintf("category_articles:%s", catID), "getcategoryarticles", url.Values{"cat_id": []string{catID}})
}

// RefreshArticle does the same for GetArticle.
func (s *Service) RefreshArticle(articleID string) ([]byte, error) {
	return s.refresh(fmt.Sprintf("article:%s", articleID), "getarticledata", url.Values{"id": []string{articleID}})
}

func (s *Service) refresh(cacheKey, action string, params url.Values) ([]byte, error) {
	data, err := s.fetchFromAPI(action, params)
	if err != nil {
		return nil, err
	}

	s.cache.Set(cacheKey, data)
	return data, nil
}

func (s *Service) fetchFromAPI(action string, params url.Values) ([]byte, error) {
	if params == nil {
		params = url.Values{}
	}
	params.Set("api_key", s.apiKey)
	params.Set("action", action)

	reqURL := fmt.Sprintf("%s?%s", s.baseURL, params.Encode())
	log.Printf("[DEBUG] Requesting URL: %s", reqURL)

	resp, err := s.httpClient.Get(reqURL)
	if err != nil {
		log.Printf("[ERROR] API request failed: %v", err)
		return nil, fmt.Errorf("api request failed: %w", err)
	}
	defer resp.Body.Close()

	log.Printf("[DEBUG] Response status: %d", resp.StatusCode)

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		log.Printf("[ERROR] API returned status %d, body: %s", resp.StatusCode, string(body))
		return nil, fmt.Errorf("api returned status %d", resp.StatusCode)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Printf("[ERROR] Failed to read response: %v", err)
		return nil, fmt.Errorf("failed to read response: %w", err)
	}

	log.Printf("[DEBUG] Response body length: %d bytes", len(body))
	if len(body) > 0 && len(body) < 500 {
		log.Printf("[DEBUG] Response preview: %s", string(body))
	}

	return body, nil
}
