package main

import (
	"C"
	"fmt"

	"github.com/Khan/genqlient/graphql"
)
import (
	"context"
	"net/http"
	"unsafe"

	"github.com/flowy-live/admin-cli/go/internal/graph"
	"github.com/sirupsen/logrus"
)

//export QueryGraphQL
func QueryGraphQL(query *C.char) *C.char {
	goQuery := C.GoString(query)
	result := fmt.Sprintf("GraphQL Response for: %s", goQuery)
	return C.CString(result)
}

//export GetWaitlist
func GetWaitlist() (**C.char, C.long) {
	heliosAddr := "https://helios.dev.flowy.live"
	heliosFullAddr := fmt.Sprintf("%s/%s", heliosAddr, "query")
	gqlClient := graphql.NewClient(heliosFullAddr, http.DefaultClient)

	response, err := graph.GetWaitlist(context.Background(), gqlClient)
	if err != nil {
		logrus.Error(err)
	}

	cArray := C.malloc(C.size_t(len(response.GetWaitlist)+1) * C.size_t(unsafe.Sizeof(uintptr(0))))
	arrayPtr := (*[1 << 30]*C.char)(cArray)[: len(response.GetWaitlist)+1 : len(response.GetWaitlist)+1] // Unsafe slice

	for i, s := range response.GetWaitlist {
		arrayPtr[i] = C.CString(s.Email)
	}
	arrayPtr[len(response.GetWaitlist)] = nil // Null-terminate

	return (**C.char)(cArray), 0
}

func main() {
}
