package paddle

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

// httpClient is the only implementation of Client. It is the single place that
// knows Paddle's base URLs, auth header and request shapes — swap the whole
// vendor here without the rest of the tree noticing.
type httpClient struct {
	apiKey string
	env    string
	base   string
	http   *http.Client
}

func newHTTPClient(apiKey, env string) (Client, error) {
	if apiKey == "" {
		return nil, fmt.Errorf("paddle: empty API key")
	}
	base := "https://sandbox-api.paddle.com"
	if env == "production" {
		base = "https://api.paddle.com"
	}
	return &httpClient{
		apiKey: apiKey,
		env:    env,
		base:   base,
		http:   &http.Client{Timeout: 20 * time.Second},
	}, nil
}

func (c *httpClient) Env() string { return c.env }

// do sends a JSON request and decodes the `data` envelope Paddle wraps every
// response in. A non-2xx is returned as an error carrying the body, so a
// configuration or auth failure is loud rather than silent.
func (c *httpClient) do(ctx context.Context, method, path string, body any, out any) error {
	var buf io.Reader
	if body != nil {
		b, err := json.Marshal(body)
		if err != nil {
			return fmt.Errorf("paddle: marshal %s %s: %w", method, path, err)
		}
		buf = bytes.NewReader(b)
	}
	req, err := http.NewRequestWithContext(ctx, method, c.base+path, buf)
	if err != nil {
		return fmt.Errorf("paddle: build %s %s: %w", method, path, err)
	}
	req.Header.Set("Authorization", "Bearer "+c.apiKey)
	req.Header.Set("Content-Type", "application/json")

	res, err := c.http.Do(req)
	if err != nil {
		return fmt.Errorf("paddle: %s %s: %w", method, path, err)
	}
	defer res.Body.Close()
	raw, _ := io.ReadAll(res.Body)
	if res.StatusCode < 200 || res.StatusCode >= 300 {
		return fmt.Errorf("paddle: %s %s returned %d: %s", method, path, res.StatusCode, string(raw))
	}
	if out == nil {
		return nil
	}
	if err := json.Unmarshal(raw, out); err != nil {
		return fmt.Errorf("paddle: decode %s %s: %w", method, path, err)
	}
	return nil
}

type updateSubscriptionRequest struct {
	Items                []reqItem `json:"items"`
	ProrationBillingMode string    `json:"proration_billing_mode"`
}

type reqItem struct {
	PriceID  string `json:"price_id"`
	Quantity int    `json:"quantity"`
}

func (c *httpClient) UpdateSubscriptionItems(ctx context.Context, subID string, items []LineItem) error {
	if subID == "" {
		return fmt.Errorf("paddle: empty subscription id")
	}
	reqItems := make([]reqItem, 0, len(items))
	for _, it := range items {
		reqItems = append(reqItems, reqItem{PriceID: it.PriceID, Quantity: it.Quantity})
	}
	return c.do(ctx, http.MethodPatch, "/subscriptions/"+subID, updateSubscriptionRequest{
		Items:                reqItems,
		ProrationBillingMode: "prorated_immediately",
	}, nil)
}

// UpdateSubscriptionCustomData patches custom_data only. Paddle replaces the
// whole object, so callers pass every key they want to keep.
func (c *httpClient) UpdateSubscriptionCustomData(ctx context.Context, subID string, data map[string]string) error {
	if subID == "" {
		return fmt.Errorf("paddle: empty subscription id")
	}
	return c.do(ctx, http.MethodPatch, "/subscriptions/"+subID, struct {
		CustomData map[string]string `json:"custom_data"`
	}{CustomData: data}, nil)
}

func (c *httpClient) PortalSession(ctx context.Context, customerID string) (string, error) {
	if customerID == "" {
		return "", fmt.Errorf("paddle: empty customer id")
	}
	var out struct {
		Data struct {
			URLs struct {
				General struct {
					Overview string `json:"overview"`
				} `json:"general"`
			} `json:"urls"`
		} `json:"data"`
	}
	if err := c.do(ctx, http.MethodPost,
		"/customers/"+customerID+"/portal-sessions", struct{}{}, &out); err != nil {
		return "", err
	}
	return out.Data.URLs.General.Overview, nil
}
