package service

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
)

type SimpleProxy struct {
	regionUrlMap map[string]string
}

func NewSimpleProxy(regionUrlMap map[string]string) *SimpleProxy {
	return &SimpleProxy{
		regionUrlMap: regionUrlMap,
	}
}

func (s *SimpleProxy) CountAttackLogs(ctx context.Context, region_code string, serviceID uint32) (int64, error) {
	remoteUrl, err := url.Parse(s.regionUrlMap[region_code])
	if err != nil {
		return 0, err
	}

	remoteUrl = remoteUrl.JoinPath("/api/v2/waf/attack/log/count")

	remoteUrl.RawQuery = fmt.Sprintf("service_id=%d&region_code=%s", serviceID, region_code)
	resp, err := http.Get(remoteUrl.String())
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return 0, fmt.Errorf("failed to count attack logs: %s", resp.Status)
	}
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return 0, err
	}

	type Response struct {
		APIVersion string `json:"apiVersion"`
		Code       string `json:"code"`
		Message    string `json:"message"`
		StatusCode int    `json:"status_code"`
		Data       int64  `json:"data"`
	}

	var response Response
	if err := json.Unmarshal(body, &response); err != nil {
		return 0, err
	}

	if response.Code != "OK" {
		return 0, fmt.Errorf("failed to count attack logs: %s", response.Message)
	}

	return response.Data, nil

}
