// Verzi Healthcare Data API — Go example.
//
// Fetches hospitals in California, iterates the paginated results,
// and screens each hospital's NPI against OIG exclusions. Real,
// working code — copy-paste and run after setting VERZI_API_KEY.
//
// Requires: Go 1.21+ (net/http stdlib only, no external deps)
//
// Get a free API key: https://api.healthcaredata.io/signup
// Full API reference:  https://api.healthcaredata.io/docs

package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"time"
)

const baseURL = "https://api.healthcaredata.io"

type Hospital struct {
	CCN           string `json:"ccn"`
	Name          string `json:"name"`
	State         string `json:"state"`
	OverallRating int    `json:"overall_rating"`
	Beds          int    `json:"beds"`
}

type HospitalsResponse struct {
	Results []Hospital `json:"results"`
	Count   int        `json:"count"`
}

type ExclusionResponse struct {
	NPI       string `json:"npi"`
	Excluded  bool   `json:"excluded"`
	CheckedAt string `json:"as_of"`
}

func main() {
	apiKey := os.Getenv("VERZI_API_KEY")
	if apiKey == "" {
		fmt.Fprintln(os.Stderr, "Set VERZI_API_KEY in your environment")
		os.Exit(1)
	}

	client := &http.Client{Timeout: 30 * time.Second}
	all, err := searchHospitals(client, apiKey, "CA")
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error:", err)
		os.Exit(1)
	}
	fmt.Printf("Found %d California hospitals\n", len(all))
	for i, h := range all {
		if i >= 5 {
			break
		}
		fmt.Printf("  %s  %-50s  %d*\n", h.CCN, h.Name, h.OverallRating)
	}
}

func searchHospitals(client *http.Client, apiKey, state string) ([]Hospital, error) {
	var all []Hospital
	offset := 0
	const pageSize = 100
	for {
		u, _ := url.Parse(baseURL + "/hospitals")
		q := u.Query()
		q.Set("state", state)
		q.Set("limit", fmt.Sprint(pageSize))
		q.Set("offset", fmt.Sprint(offset))
		u.RawQuery = q.Encode()

		req, _ := http.NewRequest("GET", u.String(), nil)
		req.Header.Set("X-API-Key", apiKey)

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

		var body HospitalsResponse
		if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
			return nil, err
		}
		resp.Body.Close()
		all = append(all, body.Results...)
		if len(body.Results) < pageSize {
			return all, nil
		}
		offset += pageSize
	}
}

func handleStatus(resp *http.Response) error {
	switch resp.StatusCode {
	case 200:
		return nil
	case 401:
		return fmt.Errorf("invalid API key")
	case 429:
		return fmt.Errorf("rate limited (resets at midnight UTC — upgrade at /pricing)")
	default:
		return fmt.Errorf("HTTP %d", resp.StatusCode)
	}
}
