package lkgateway

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

// postJSON отправляет JSON через любой метод (POST/PATCH/PUT). Используется
// для callback'ов в ЛК.
func postJSON(ctx context.Context, c *http.Client, url, method string, body any) error {
	raw, err := json.Marshal(body)
	if err != nil {
		return err
	}
	req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(raw))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := c.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode >= 400 {
		buf, _ := io.ReadAll(resp.Body)
		return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(buf))
	}
	return nil
}

// writeJSON удобный writer JSON-ответа со статусом.
func writeJSON(w http.ResponseWriter, status int, body any) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(body)
}

// writeError формирует ErrorResponse по контракту ESIA Finance.
func writeError(w http.ResponseWriter, status int, code, title, message string) {
	writeJSON(w, status, ErrorResponse{
		Error:  true,
		Status: status,
		Code:   code,
		Title:  title,
		Meta:   &ErrorMeta{Message: message},
	})
}
