package lkemulator

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

// GatewayClient — клиент к lk-gateway по REST.
type GatewayClient struct {
	baseURL string
	httpc   *http.Client
}

// NewGatewayClient — конструктор.
func NewGatewayClient(baseURL string) *GatewayClient {
	return &GatewayClient{
		baseURL: baseURL,
		httpc:   &http.Client{Timeout: 10 * time.Second},
	}
}

// CreateClaim шлёт POST /api/v1/back_office/claims/ и возвращает ответ.
func (c *GatewayClient) CreateClaim(ctx context.Context, body map[string]any) (map[string]any, error) {
	raw, err := json.Marshal(body)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost,
		c.baseURL+"/api/v1/back_office/claims/", bytes.NewReader(raw))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := c.httpc.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	out, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode >= 400 {
		return nil, fmt.Errorf("lk-gateway HTTP %d: %s", resp.StatusCode, string(out))
	}
	var parsed map[string]any
	if err := json.Unmarshal(out, &parsed); err != nil {
		return nil, fmt.Errorf("lk-gateway: разбор JSON: %w; raw: %s", err, string(out))
	}
	return parsed, nil
}

// SetCallbackURL сообщает gateway свой URL — куда слать PATCH callback'и.
func (c *GatewayClient) SetCallbackURL(ctx context.Context, url string) error {
	req, err := http.NewRequestWithContext(ctx, http.MethodPost,
		c.baseURL+"/admin/api/callback-url?url="+url, nil)
	if err != nil {
		return err
	}
	resp, err := c.httpc.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode >= 400 {
		buf, _ := io.ReadAll(resp.Body)
		return fmt.Errorf("set callback url HTTP %d: %s", resp.StatusCode, string(buf))
	}
	return nil
}
