package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/google/uuid"
)

const (
	url     string = "https://digital.mchs.gov.ru/testing/api/instance/"
	uidMchs string = "4e0d6bf6-50f2-4d67-8131-b99b3c4a3f39"
)

type ResMchsTestType struct {
	Id              uuid.UUID `json:"id"`
	CurrentQuestion CQType    `json:"current_question"`
	CurrentAnswers  []CAType  `json:"current_answers"`
	QuestionCount   int       `json:"questions_count"`
	QuestionNumber  int       `json:"question_number"`
	QuestionStatus  []int     `json:"questions_statuses"`
	ValidAnswer     uuid.UUID `json:"valid_answer"`
	QuestionPassed  int       `json:"questions_passed"`
	ValidAnswers    string    `json:"valid_answers"`
}

type CQType struct {
	Id            uuid.UUID `json:"id"`
	Content       string    `json:"content"`
	ResourcesPath []string  `json:"resources_path"`
	Types         string    `json:"type"`
	IsAdd         bool      `json:"id_additional"`
}

type CAType struct {
	Id            uuid.UUID `json:"id"`
	Title         string    `json:"title"`
	ResourcesPath []string  `json:"resources_path"`
}

func ResMchsTestToJSON(data *ResMchsTestType) string {
	req, _ := json.Marshal(data)
	return string(req)
}

func UnmarshalJSONToType(in []byte) *ResMchsTestType {
	var data ResMchsTestType
	_ = json.Unmarshal(in, &data)
	return &data
}

type ReqAnswer struct {
	Answer uuid.UUID `json:"answer"`
}

type ReqNull struct {
	Answers string `json:"answers"`
}

func main() {
	var rN ReqNull
	var rA ReqAnswer
	body, _ := ReqestToSiteJSON(rN)
	fmt.Println("[")
	for i := 0; i < 520; i++ {
		d := UnmarshalJSONToType(body)
		fmt.Print(ResMchsTestToJSON(d), ",\n")
		rA.Answer = d.ValidAnswer
		body, _ = ReqestToSiteJSON(rA)
	}
	d := UnmarshalJSONToType(body)
	fmt.Println(ResMchsTestToJSON(d))
	fmt.Println("]")
}

func ReqestToSiteJSON(req any) ([]byte, error) {

	reqBodyBytes, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}

	urlr := url + uidMchs
	resp, err := http.Post(
		urlr,
		"application/json", bytes.NewBuffer(reqBodyBytes))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}

func ReqestToSite(req any) (*ResMchsTestType, error) {

	reqBodyBytes, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}

	urlr := url + uidMchs
	resp, err := http.Post(
		urlr,
		"application/json", bytes.NewBuffer(reqBodyBytes))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return UnmarshalJSONToType(body), nil
}
