package hetzner

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

func SendGetZones(token string, names ...string) []string {
	client := &http.Client{}

	var ids []string

	for _, name := range names {
		fmt.Println("Getting zone: ", name)
		req, err := http.NewRequest("GET", "https://dns.hetzner.com/api/v1/zones?name="+name, nil)
		req.Header.Add("Auth-API-Token", token)

		resp, err := client.Do(req)
		if err != nil {
			panic(err)
		}

		respBody, _ := io.ReadAll(resp.Body)

		fmt.Println("response Status : ", resp.Status)
		var responseObject struct {
			Zones []Zone
		}

		err = json.Unmarshal(respBody, &responseObject)
		if err != nil {
			panic(err)
		}

		ids = append(ids, responseObject.Zones[0].Id)
	}

	return ids
}

func SendGetRecords(token string, zoneId string) []Record {
	client := &http.Client{}

	req, err := http.NewRequest("GET", "https://dns.hetzner.com/api/v1/records?zone_id="+zoneId, nil)
	req.Header.Add("Auth-API-Token", token)

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Failure : ", err)
	}

	respBody, _ := io.ReadAll(resp.Body)

	fmt.Println("Response Status : ", resp.Status)

	var responseObject struct {
		Records []Record
	}

	err = json.Unmarshal(respBody, &responseObject)
	if err != nil {
		panic(err)
	}

	fmt.Println("Records: ", responseObject.Records)

	return responseObject.Records
}

func SendUpdateRecords(token string, records []Record) {
	client := &http.Client{}

	var recordsReq struct {
		Records []Record `json:"records"`
	}

	recordsReq.Records = records

	jsonReq, err := json.Marshal(recordsReq)
	if err != nil {
		panic(err)
	}

	fmt.Println("Request: ", string(jsonReq))

	req, err := http.NewRequest("PUT", "https://dns.hetzner.com/api/v1/records/bulk", bytes.NewBuffer(jsonReq))
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Auth-API-Token", token)
	if err != nil {
		panic(err)
	}

	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}

	respBody, _ := ioutil.ReadAll(resp.Body)

	fmt.Println("response Status: ", resp.Status)
	fmt.Println("response Body: ", string(respBody))

	var responseObject struct {
		Records       []Record `json:"records"`
		FailedRecords []Record `json:"failed_records"`
	}

	err = json.Unmarshal(respBody, &responseObject)
	if err != nil {
		panic(err)
	}

	if len(responseObject.FailedRecords) > 0 {
		fmt.Println("Failed records: ", responseObject.FailedRecords)
		panic("Failed to update records: " + string(respBody))
	}
}
