// Package hbank is a client for the HBank merchant API (v1): payments, QR codes, refunds, subscriptions and
// currencies. Standard library only.
//
//	bank := hbank.New(os.Getenv("HBANK_API_KEY"))
//	tid, err := bank.CreatePayment(ctx, hbank.PaymentRequest{Amount: "24.90", Currency: "EUR",
//		Description: "Order 1042", CallbackURL: "https://shop.example/hbank/callback"})
//	http.Redirect(w, r, bank.CheckoutURL(tid), http.StatusFound)
//
// Amounts are decimal strings in the currency's major unit ("24.90"), sent and received without going through
// float64. Use json.Number's Float64 or a decimal library to calculate with them.
package hbank

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

// Version is this SDK's version. HBank's git repository (bank.thehsi.cloud/hbank/hbank-go.git) tags it as
// v<Version>: change it whenever the SDK changes, since a published version's contents must never change.
const Version = "1.2.0"

// DefaultBaseURL is HBank's production address.
const DefaultBaseURL = "https://bank.thehsi.cloud"

// Client talks to the API. It is safe for concurrent use.
type Client struct {
	apiKey     string
	BaseURL    string
	HTTPClient *http.Client
}

// Option configures a Client.
type Option func(*Client)

// WithBaseURL sets another HBank address (e.g. a test instance).
func WithBaseURL(u string) Option { return func(c *Client) { c.BaseURL = strings.TrimRight(u, "/") } }

// WithHTTPClient sets the http.Client to use; its Timeout applies. Default: 30 second timeout.
func WithHTTPClient(h *http.Client) Option { return func(c *Client) { c.HTTPClient = h } }

// New creates a client for your secret API key.
func New(apiKey string, opts ...Option) *Client {
	c := &Client{apiKey: apiKey, BaseURL: DefaultBaseURL, HTTPClient: &http.Client{Timeout: 30 * time.Second}}
	for _, o := range opts {
		o(c)
	}
	return c
}

// Error is an error answer from the API. Code is machine-readable ("invalid_amount", "transaction_not_found",
// "invalid_api_key", ...), Status the HTTP status (0 if HBank couldn't be reached), Message the readable text some
// errors carry. Use errors.As to get it.
//
// When Code is "connection_failed" the request may or may not have reached HBank: before retrying a refund, check
// Refunded with GetPayment.
type Error struct {
	Code    string
	Status  int
	Message string
	Err     error
}

func (e *Error) Error() string {
	s := e.Code
	if e.Status != 0 {
		s += fmt.Sprintf(" (HTTP %d)", e.Status)
	}
	if e.Message != "" {
		s += ": " + e.Message
	}
	return "hbank: " + s
}

func (e *Error) Unwrap() error { return e.Err }

// IsCode reports whether err is an *Error with the given code.
func IsCode(err error, code string) bool {
	var e *Error
	return errors.As(err, &e) && e.Code == code
}

// ── Types ───────────────────────────────────────────────────

// Payment is a payment (or a refund, Type "refund").
type Payment struct {
	ID             string      `json:"id"` // "tx_…": a random string, not a number
	Type           string      `json:"type"`
	Amount         json.Number `json:"amount"`
	Currency       string      `json:"currency"`
	Status         string      `json:"status"` // pending, completed or aborted
	Description    string      `json:"description"`
	Reference      *string     `json:"reference"` // set once completed
	PaymentCode    *string     `json:"payment_code"`
	Refunded       json.Number `json:"refunded"`
	Refundable     json.Number `json:"refundable"`
	RefundOf       *string     `json:"refund_of"`
	SubscriptionID *string     `json:"subscription_id"` // "sub_…"
	// SubscriptionIDs lists every subscription the payment belongs to: the one it charged, or all those a checkout of
	// several started (CreateSubscriptionsCheckout).
	SubscriptionIDs []string `json:"subscription_ids"`
}

// Completed reports whether the payment is paid. Check it before handing out goods.
func (p *Payment) Completed() bool { return p.Status == "completed" }

// PaymentCode is a QR code for a pending payment: put URL in a QR code, or show the SVG at QRSVG.
type PaymentCode struct {
	Code  string `json:"code"`
	URL   string `json:"url"`
	QRSVG string `json:"qr_svg"`
}

type Refund struct {
	ID        string      `json:"id"`
	Amount    json.Number `json:"amount"`
	Currency  string      `json:"currency"`
	Reference string      `json:"reference"`
	Reason    *string     `json:"reason"`
}

// RefundResult is the refund and the refunded payment, with updated Refunded / Refundable.
type RefundResult struct {
	Refund  Refund  `json:"refund"`
	Payment Payment `json:"transaction"`
}

type Subscription struct {
	ID                   string      `json:"id"`            // "sub_…": a random string, not a number
	Status               string      `json:"status"`        // offered, active or canceled
	ActivePeriod         bool        `json:"active_period"` // within a paid period: give access while true
	Amount               json.Number `json:"amount"`
	Currency             string      `json:"currency"`
	Interval             string      `json:"interval"` // day, week, month or year
	IntervalCount        int         `json:"interval_count"`
	Description          *string     `json:"description"`
	URL                  string      `json:"url"` // send this to the customer
	QRSVG                string      `json:"qr_svg"`
	SubscribedAt         *time.Time  `json:"subscribed_at"`
	SubscribedForDays    *int        `json:"subscribed_for_days"`
	SubscribedForSeconds *int64      `json:"subscribed_for_seconds"`
	Canceled             bool        `json:"canceled"`
	CanceledAt           *time.Time  `json:"canceled_at"`
	CanceledBy           *string     `json:"canceled_by"` // customer, merchant, bank or schedule
	CurrentPeriodStart   *time.Time  `json:"current_period_start"`
	CurrentPeriodEnd     *time.Time  `json:"current_period_end"`
	NextChargeAt         *time.Time  `json:"next_charge_at"`
	EndsAt               *time.Time  `json:"ends_at"`
	LastDay              *time.Time  `json:"last_day"`
	Charges              int         `json:"charges"`
	LastError            *string     `json:"last_error"`
	Customer             *struct {
		Name string `json:"name"`
	} `json:"customer"`
}

// SubscriptionCheckout is a subscription's first payment: hand TransactionID to the pay button / hosted checkout.
type SubscriptionCheckout struct {
	TransactionID string       `json:"transaction_id"`
	Subscription  Subscription `json:"subscription"`
}

// SubscriptionsCheckout is one first payment for several subscriptions: paying TransactionID starts all of
// Subscriptions (in your order).
type SubscriptionsCheckout struct {
	TransactionID string         `json:"transaction_id"`
	Subscriptions []Subscription `json:"subscriptions"`
}

// SubscriptionCheckoutItem is one subscription in CreateSubscriptionsCheckout: one you already offered
// (ExistingSubscription) or a new offer (NewSubscription).
type SubscriptionCheckoutItem struct {
	ID    string               // "sub_…" of an offer, or ""
	Offer *SubscriptionRequest // the new offer's fields when ID is ""; its CallbackURL is ignored
}

// ExistingSubscription is a subscription you already offered.
func ExistingSubscription(id string) SubscriptionCheckoutItem {
	return SubscriptionCheckoutItem{ID: id}
}

// NewSubscription is a new offer, made with the checkout.
func NewSubscription(s SubscriptionRequest) SubscriptionCheckoutItem {
	return SubscriptionCheckoutItem{Offer: &s}
}

// MarshalJSON writes the offer's id, or the new offer's fields.
func (i SubscriptionCheckoutItem) MarshalJSON() ([]byte, error) {
	if i.ID != "" || i.Offer == nil {
		return json.Marshal(i.ID)
	}
	offer := withCount(*i.Offer)
	offer.CallbackURL = ""
	return json.Marshal(offer)
}

// SubscriptionsCheckoutRequest is the input to CreateSubscriptionsCheckout.
type SubscriptionsCheckoutRequest struct {
	Subscriptions []SubscriptionCheckoutItem `json:"subscriptions"`         // up to 20, in one currency
	Description   string                     `json:"description,omitempty"` // default: the subscriptions' descriptions
	CallbackURL   string                     `json:"callback_url,omitempty"`
}

// Rate: ToRate converts from into to, FromRate the other way.
type Rate struct {
	ToRate   json.Number `json:"to_rate"`
	FromRate json.Number `json:"from_rate"`
}

// PaymentRequest is the input to CreatePayment.
type PaymentRequest struct {
	Amount      string `json:"amount"`   // e.g. "24.90"
	Currency    string `json:"currency"` // ISO code, e.g. "EUR"
	Description string `json:"description,omitempty"`
	CallbackURL string `json:"callback_url,omitempty"` // required for the hosted checkout
}

// SubscriptionRequest is the input to CreateSubscription and CreateSubscriptionCheckout.
type SubscriptionRequest struct {
	Amount        string `json:"amount"`
	Currency      string `json:"currency"`
	Interval      string `json:"interval"`                 // day, week, month or year
	IntervalCount int    `json:"interval_count,omitempty"` // 1 to 120; 0 means 1
	Description   string `json:"description,omitempty"`
	CallbackURL   string `json:"callback_url,omitempty"` // CreateSubscriptionCheckout only
}

// ── Payments ────────────────────────────────────────────────

// CreatePayment creates a pending payment request and returns its transaction id (a random string like
// "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v"; store it as text). It stays payable for one hour.
func (c *Client) CreatePayment(ctx context.Context, p PaymentRequest) (string, error) {
	var out struct {
		TransactionID string `json:"transaction_id"`
	}
	return out.TransactionID, c.do(ctx, http.MethodPost, "payment/request", p, &out)
}

// CreatePaymentCode gives a pending payment a QR code / link. Calling it again returns the same code.
func (c *Client) CreatePaymentCode(ctx context.Context, transactionID string) (*PaymentCode, error) {
	var out PaymentCode
	return &out, c.do(ctx, http.MethodPost, "payment/code", map[string]string{"transaction_id": transactionID}, &out)
}

// GetPayment returns the current state of one of your payments.
func (c *Client) GetPayment(ctx context.Context, transactionID string) (*Payment, error) {
	var out struct {
		Transaction Payment `json:"transaction"`
	}
	err := c.do(ctx, http.MethodPost, "payment/details", map[string]string{"transaction_id": transactionID}, &out)
	return &out.Transaction, err
}

// Refund refunds (part of) a completed payment: amount in its currency, or everything that's left when "". reason
// (optional, up to 200 characters) is shown to the customer.
func (c *Client) Refund(ctx context.Context, transactionID string, amount, reason string) (*RefundResult, error) {
	body := map[string]any{"transaction_id": transactionID}
	if amount != "" {
		body["amount"] = amount
	}
	if reason != "" {
		body["reason"] = reason
	}
	var out RefundResult
	return &out, c.do(ctx, http.MethodPost, "payment/refund", body, &out)
}

// CheckoutURL is the hosted checkout (card number + PIN) for a payment. The payment needs a callback URL.
func (c *Client) CheckoutURL(transactionID string) string {
	return c.BaseURL + "/api/payment?tid=" + url.QueryEscape(transactionID)
}

// ── Subscriptions ───────────────────────────────────────────

// CreateSubscription offers a subscription. Send the customer its URL.
func (c *Client) CreateSubscription(ctx context.Context, s SubscriptionRequest) (*Subscription, error) {
	s.CallbackURL = ""
	var out struct {
		Subscription Subscription `json:"subscription"`
	}
	err := c.do(ctx, http.MethodPost, "subscriptions", withCount(s), &out)
	return &out.Subscription, err
}

// CreateSubscriptionCheckout offers a subscription and creates its first payment, for the pay button.
func (c *Client) CreateSubscriptionCheckout(ctx context.Context, s SubscriptionRequest) (*SubscriptionCheckout, error) {
	var out SubscriptionCheckout
	return &out, c.do(ctx, http.MethodPost, "subscriptions/checkout", withCount(s), &out)
}

// CreateSubscriptionsCheckout creates one first payment for several subscriptions (up to 20, one currency): offers
// you made or new ones. Paying it starts them all; after that each renews on its own. When one is refused, nothing
// is offered.
func (c *Client) CreateSubscriptionsCheckout(ctx context.Context, r SubscriptionsCheckoutRequest) (*SubscriptionsCheckout, error) {
	var out SubscriptionsCheckout
	return &out, c.do(ctx, http.MethodPost, "subscriptions/checkout", r, &out)
}

// CheckoutSubscription creates a new first payment for a subscription already offered ("not_open" once someone
// subscribed). callbackURL may be "".
func (c *Client) CheckoutSubscription(ctx context.Context, subscriptionID string, callbackURL string) (*SubscriptionCheckout, error) {
	body := map[string]string{}
	if callbackURL != "" {
		body["callback_url"] = callbackURL
	}
	var out SubscriptionCheckout
	return &out, c.do(ctx, http.MethodPost, "subscriptions/"+url.PathEscape(subscriptionID)+"/checkout", body, &out)
}

// ListSubscriptions returns your subscriptions, newest first (up to 100).
func (c *Client) ListSubscriptions(ctx context.Context) ([]Subscription, error) {
	var out struct {
		Subscriptions []Subscription `json:"subscriptions"`
	}
	return out.Subscriptions, c.do(ctx, http.MethodGet, "subscriptions", nil, &out)
}

func (c *Client) GetSubscription(ctx context.Context, subscriptionID string) (*Subscription, error) {
	var out struct {
		Subscription Subscription `json:"subscription"`
	}
	err := c.do(ctx, http.MethodGet, "subscriptions/"+url.PathEscape(subscriptionID), nil, &out)
	return &out.Subscription, err
}

// CancelSubscription stops future charges. It stays in its active period until CurrentPeriodEnd.
func (c *Client) CancelSubscription(ctx context.Context, subscriptionID string) (*Subscription, error) {
	var out struct {
		Subscription Subscription `json:"subscription"`
	}
	err := c.do(ctx, http.MethodPost, "subscriptions/"+url.PathEscape(subscriptionID)+"/cancel", map[string]any{}, &out)
	return &out.Subscription, err
}

// ── Currencies ──────────────────────────────────────────────

func (c *Client) Convert(ctx context.Context, amount, from, to string) (json.Number, error) {
	q := url.Values{"amount": {amount}, "currency_from": {from}, "currency_to": {to}}
	var out struct {
		Amount json.Number `json:"amount"`
	}
	return out.Amount, c.do(ctx, http.MethodGet, "currency/convert?"+q.Encode(), nil, &out)
}

func (c *Client) Rate(ctx context.Context, from, to string) (*Rate, error) {
	q := url.Values{"currency_from": {from}, "currency_to": {to}}
	var out Rate
	return &out, c.do(ctx, http.MethodGet, "currency/rate?"+q.Encode(), nil, &out)
}

// ── Transport ───────────────────────────────────────────────

func withCount(s SubscriptionRequest) SubscriptionRequest {
	if s.IntervalCount == 0 {
		s.IntervalCount = 1
	}
	return s
}

func (c *Client) do(ctx context.Context, method, path string, body any, out any) error {
	var reader io.Reader
	if body != nil {
		data, err := json.Marshal(body)
		if err != nil {
			return err
		}
		reader = bytes.NewReader(data)
	}
	req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+"/api/v1/"+path, reader)
	if err != nil {
		return err
	}
	req.Header.Set("Authorization", "Bearer "+c.apiKey)
	req.Header.Set("Accept", "application/json")
	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}

	res, err := c.HTTPClient.Do(req)
	if err != nil {
		return &Error{Code: "connection_failed", Message: err.Error(), Err: err}
	}
	defer res.Body.Close()
	raw, err := io.ReadAll(io.LimitReader(res.Body, 10<<20))
	if err != nil {
		return &Error{Code: "connection_failed", Status: res.StatusCode, Message: err.Error(), Err: err}
	}

	text := strings.TrimSpace(string(raw))
	switch res.StatusCode {
	case http.StatusUnauthorized:
		return &Error{Code: "missing_api_key", Status: res.StatusCode, Message: text}
	case http.StatusForbidden:
		return &Error{Code: "invalid_api_key", Status: res.StatusCode, Message: text}
	}

	var envelope struct {
		Success *bool  `json:"success"`
		Error   string `json:"error"`
		Message string `json:"message"`
	}
	if err := json.Unmarshal(raw, &envelope); err != nil {
		if len(text) > 200 {
			text = text[:200]
		}
		return &Error{Code: "invalid_response", Status: res.StatusCode, Message: text, Err: err}
	}
	if res.StatusCode < 200 || res.StatusCode >= 300 || (envelope.Success != nil && !*envelope.Success) {
		code := envelope.Error
		if code == "" {
			code = fmt.Sprintf("http_%d", res.StatusCode)
		}
		return &Error{Code: code, Status: res.StatusCode, Message: envelope.Message}
	}
	dec := json.NewDecoder(bytes.NewReader(raw))
	dec.UseNumber()
	if err := dec.Decode(out); err != nil {
		return &Error{Code: "invalid_response", Status: res.StatusCode, Message: err.Error(), Err: err}
	}
	return nil
}
