package clients

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

type EmailReportRegenerateRequest struct {
	DivisionID string `json:"divisionId"`
	DeviceType int    `json:"deviceType"`
	DateTime   int    `json:"dateTime"`
	QueueId    string `json:"queueId"`
}

type ExceptionReportClient struct {
	BaseURL    string
	HTTPClient *http.Client
}

func NewExceptionReportClient(url string) *ExceptionReportClient {
	return &ExceptionReportClient{
		BaseURL: url,
		// the api answers after the report is regenerated, a big division takes a while
		HTTPClient: &http.Client{
			Timeout: 5 * time.Minute,
		},
	}
}

func (c *ExceptionReportClient) RegenerateReport(ctx context.Context, req EmailReportRegenerateRequest) error {
	if c.BaseURL == "" {
		return fmt.Errorf("LOCAL_URL environment variable is not set")
	}

	params := url.Values{}
	params.Set("divisionId", req.DivisionID)
	params.Set("deviceType", strconv.Itoa(req.DeviceType))
	params.Set("startDateTime", strconv.FormatInt(int64(req.DateTime), 10))
	params.Set("queueId", req.QueueId)

	endpoint := c.BaseURL + "?" + params.Encode()

	httpReq, err := http.NewRequestWithContext(
		ctx,
		http.MethodGet,
		endpoint,
		nil,
	)
	if err != nil {
		return fmt.Errorf("create request: %w", err)
	}

	resp, err := c.HTTPClient.Do(httpReq)
	if err != nil {
		return fmt.Errorf("call regeneration API: %w", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("read response: %w", err)
	}

	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		return fmt.Errorf(
			"exception report API failed: status=%d, response=%s",
			resp.StatusCode,
			string(body),
		)
	}

	return nil
}
