package platform

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"strings"
	"time"
)

// FetchOAuthConfig pulls the Auth Broker coordinates from the cdrop backend's
// /api/auth/config (broker_url = the broker's public origin). The desktop runs the
// broker device-authorization flow (RFC 8252 loopback PKCE) against that broker,
// minting a cdrop-scoped machine token. apiBase is the backend origin, e.g.
// https://drop.commilitia.net.
func FetchOAuthConfig(ctx context.Context, apiBase string) (OAuthConfig, error) {
	endpoint := strings.TrimRight(apiBase, "/") + "/api/auth/config"
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
	if err != nil {
		return OAuthConfig{}, fmt.Errorf("oauth: build config request: %w", err)
	}
	req.Header.Set("Accept", "application/json")

	client := &http.Client{Timeout: 15 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return OAuthConfig{}, fmt.Errorf("oauth: fetch config: %w", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return OAuthConfig{}, fmt.Errorf("oauth: config endpoint status %d", resp.StatusCode)
	}

	var c struct {
		BrokerURL string `json:"broker_url"`
		App       string `json:"broker_app"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&c); err != nil {
		return OAuthConfig{}, fmt.Errorf("oauth: decode config: %w", err)
	}

	app := c.App
	if app == "" {
		app = "cdrop"
	}
	cfg := OAuthConfig{BrokerURL: c.BrokerURL, App: app}
	if cfg.BrokerURL == "" {
		return OAuthConfig{}, errors.New("oauth: backend config missing broker_url")
	}
	return cfg, nil
}
