package service

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

	"gitlab.com/tensorsecurity-rd/waf-console/internal/utils"
)

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
	}
	var response utils.SuccessResponse
	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.(int64), nil

}
