#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winhttp.h>
#include <stdio.h>
#include <string.h>

#pragma comment(lib, "winhttp.lib")

int main(void)
{
	static const wchar_t headers[] =
		L"X-API-Key: YOUR_API_KEY\r\n"
		L"Idempotency-Key: create-customer-0001\r\n"
		L"Content-Type: application/json\r\n";
	static const char body[] =
		"{\"serviceid\":2,\"name\":\"Customer Name\","
		"\"email\":\"customer@example.com\"}";
	HINTERNET session;
	HINTERNET connection;
	HINTERNET request;
	DWORD status = 0;
	DWORD status_size = sizeof(status);
	DWORD available;
	DWORD read_count;
	char buffer[4096];
	char response[65536];
	size_t response_length = 0;

	session = WinHttpOpen(L"StarBonding-OEM/1.0",
		WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, NULL, NULL, 0);
	if (!session)
		return 1;
	connection = WinHttpConnect(session, L"starbonding.com",
		INTERNET_DEFAULT_HTTPS_PORT, 0);
	request = connection ? WinHttpOpenRequest(connection, L"POST",
		L"/api/v1/create.account.php", NULL, WINHTTP_NO_REFERER,
		WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : NULL;
	if (!request || !WinHttpSendRequest(request, headers, (DWORD)-1,
		(void *)body, (DWORD)(sizeof(body) - 1), (DWORD)(sizeof(body) - 1), 0) ||
	    !WinHttpReceiveResponse(request, NULL)) {
		fprintf(stderr, "WinHTTP failed: %lu\n", GetLastError());
		return 1;
	}
	WinHttpQueryHeaders(request,
		WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
		NULL, &status, &status_size, NULL);
	while (WinHttpQueryDataAvailable(request, &available) && available) {
		DWORD wanted = available < sizeof(buffer) ? available : sizeof(buffer);
		if (!WinHttpReadData(request, buffer, wanted, &read_count))
			break;
		if (response_length + read_count >= sizeof(response)) {
			fprintf(stderr, "response is too large\n");
			return 1;
		}
		memcpy(response + response_length, buffer, read_count);
		response_length += read_count;
		fwrite(buffer, 1, read_count, stdout);
	}
	response[response_length] = 0;
	fputc('\n', stdout);
	WinHttpCloseHandle(request);
	WinHttpCloseHandle(connection);
	WinHttpCloseHandle(session);
	return status >= 200 && status < 300 &&
		strstr(response, "\"success\":true") != NULL ? 0 : 1;
}
