package apipinger

import (
	"bytes"
	"context"
	"fmt"
	"net/http"
	"sync"
	"time"
)

// APIPinger represents a pinger for an API.
type APIPinger struct {
	APIURL     string
	Method     string
	Payload    string
	ReturnCode int
}

// Ping pings the specified API URL and sends the result to the results channel.
func (p *APIPinger) Ping(ctx context.Context, wg *sync.WaitGroup, results chan<- string, token string) {
	defer wg.Done()

	req, err := http.NewRequestWithContext(ctx, p.Method, p.APIURL, bytes.NewBuffer([]byte(p.Payload)))
	if err != nil {
		results <- fmt.Sprintf("Error creating request: %v", err)
		return
	}

	// Add the Bearer token to the request header
	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json") // Set content type if payload is JSON

	startTime := time.Now()
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		results <- fmt.Sprintf("Error pinging API: %v", err)
		return
	}
	defer resp.Body.Close()

	latency := time.Since(startTime) // Calculate the latency

	if resp.StatusCode == http.StatusOK {
		results <- fmt.Sprintf("API %s ping successful: %s, latency: %v", p.APIURL, resp.Status, latency)
	} else {
		results <- fmt.Sprintf("API %s ping failed: %s, latency: %v", p.APIURL, resp.Status, latency)
	}
}
