package main

import (
	bytes2 "bytes"
	"io"
	"log"
	"net/http"
	"strconv"
	"time"
)

func main() {

	jsonData := bytes2.NewReader([]byte(`{"val":"1"}`))

	http.DefaultClient = &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}

	response, err := http.Post("http://localhost:8082/start", "application/json", jsonData)
	if err != nil {
		log.Fatal(err)
	}

	if response.StatusCode != http.StatusAccepted {
		log.Fatal("could not start process. got status ", response.Status)
	}

	resultStatus := http.StatusOK
	for resultStatus == http.StatusOK {
		waitTime := response.Header.Get("Retry-After")
		if waitTime != "" {
			sleep, err := strconv.Atoi(waitTime)
			if err != nil {
				log.Fatal(err)
			}
			log.Println("sleep for", sleep)
			time.Sleep(time.Duration(sleep) * time.Second)
		}

		newUrl := response.Header.Get("Location")
		log.Println("executing request to", newUrl)
		response, err = http.Get(newUrl)
		if err != nil {
			log.Fatal(err)
		}
		resultStatus = response.StatusCode
		log.Println("got status", resultStatus)
	}

	newUrl := response.Header.Get("Location")
	response, err = http.Get(newUrl)
	if err != nil {
		log.Fatal(err)
	}
	defer response.Body.Close()
	bytes, err := io.ReadAll(response.Body)
	if err != nil {
		log.Fatal(err)
	}

	log.Println("result is:", string(bytes))

}
