package aiopscli

import (
	"context"
	"fmt"
	"net/http"

	"github.com/go-resty/resty/v2"
)

type Client interface {
}

type client struct {
	addr   string
	apiKey string
	raw    *resty.Client
}

func NewClient(addr, apiKey string) (Client, error) {
	httpClient := resty.New().
		SetTransport(http.DefaultTransport).
		SetScheme("https").
		SetBaseURL(addr).
		OnBeforeRequest(func(c *resty.Client, r *resty.Request) error {
			r.Header.Set("X-API-KEY", apiKey)
			return nil
		}).
		OnAfterResponse(func(c *resty.Client, r *resty.Response) error {
			if !r.IsSuccess() {
				return fmt.Errorf("status: %s, body: %s", r.Status(), string(r.Body()))
			}
			return nil
		})

	c := &client{
		addr:   addr,
		apiKey: apiKey,
		raw:    httpClient,
	}

	return c, nil
}

func (c *client) JiraSummaryTimelineAsync(ctx context.Context, issueID string, req JiraSummarizeTimelineRequest) (*LongRunningOperation, error) {
	resp := &LongRunningOperation{}
	_, err := c.raw.R().
		SetContext(ctx).
		SetPathParam("issue_id", issueID).
		SetBody(req).
		SetResult(resp).
		Post("/api/v1/aiops/jira/issues/{issue_id}/summarize_timeline_async")
	if err != nil {
		return nil, fmt.Errorf("failed to request aiops server: %w", err)
	}

	return resp, nil
}

func (c *client) KitSummaryTimelineFromLarkMessages(ctx context.Context, req KitSummaryTimelineFromLarkMessagesRequest) (*LongRunningOperation, error) {
	resp := &LongRunningOperation{}
	_, err := c.raw.R().
		SetContext(ctx).
		SetBody(req).
		SetResult(resp).
		Post("/api/v1/aiops/kit/lark/summarize_timeline_async")
	if err != nil {
		return nil, fmt.Errorf("failed to request aiops server: %w", err)
	}

	return resp, nil
}
