package dify

import (
	"errors"
	"github.com/go-resty/resty/v2"
)

type SessionResponse struct {
	Limit   int            `json:"limit"`
	HasMore bool           `json:"has_more"`
	Data    []SessionDatum `json:"data"`
}

type SessionDatum struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Inputs    Inputs `json:"inputs"`
	Status    string `json:"status"`
	CreatedAt int64  `json:"created_at"`
}

type Inputs map[string]string

type HistoryResponse struct {
	Limit   int       `json:"limit"`
	HasMore bool      `json:"has_more"`
	Data    []History `json:"data"`
}

type History struct {
	ID             string `json:"id"`
	ConversationId string `json:"conversation_id"`
	Inputs         Inputs `json:"inputs"`
	Query          string `json:"query"`
	Answer         string `json:"answer"`
	CreatedAt      int64  `json:"created_at"`
}

type DeleteSessionResponse struct {
	Result string `json:"result"`
}

type RenameSessionResp struct {
	ID           string `json:"id"`
	Name         string `json:"name"`
	Inputs       Inputs `json:"inputs"`
	Introduction string `json:"introduction"`
	CreatedAt    int64  `json:"created_at"`
}

// GetSessionList 获取会话列表
func GetSessionList(baseUrl, token, user, lastId, limit string) (*SessionResponse, error) {
	data := &SessionResponse{}
	resp, err := NewDifyResty(baseUrl, token).
		R().
		SetResult(&data).
		SetQueryParam("user", user).
		SetQueryParam("last_id", lastId).
		SetQueryParam("limit", limit).
		Get("/conversations")

	if err != nil {
		return nil, err
	}

	if resp.IsError() {
		return nil, errors.New(resp.String())
	}

	return data, nil
}

// DeleteSession 删除会话
func DeleteSession(baseUrl, token, user, conversationId string) (*DeleteSessionResponse, error) {
	data := &DeleteSessionResponse{}
	body := make(map[string]string)
	body["user"] = user
	_, err := NewDifyResty(baseUrl, token).
		R().
		SetResult(&data).
		SetBody(body).
		Delete("/conversations/" + conversationId)

	if err != nil {
		return nil, err
	}

	return data, nil
}

// RenameSession 会话重命名
func RenameSession(baseUrl, token, user, name, conversationId string) (*DeleteSessionResponse, error) {
	data := &DeleteSessionResponse{}
	body := make(map[string]string)
	body["user"] = user
	body["name"] = name
	resp, err := NewDifyResty(baseUrl, token).
		R().
		SetResult(&data).
		SetBody(body).
		Post("/conversations/" + conversationId + "/name")

	if err != nil {
		return nil, err
	}

	if resp.IsError() {
		return nil, errors.New(resp.String())
	}

	return data, nil
}

// GetChatHistory 获取历史会话
func GetChatHistory(baseUrl, token, user, conversationId, firstId, limit string) (*HistoryResponse, error) {
	data := &HistoryResponse{}
	resp, err := NewDifyResty(baseUrl, token).
		R().
		SetResult(&data).
		SetQueryParam("user", user).
		SetQueryParam("conversation_id", conversationId).
		SetQueryParam("first_id", firstId).
		SetQueryParam("limit", limit).
		Get("/messages")

	if err != nil {
		return nil, err
	}

	if resp.IsError() {
		return nil, errors.New(resp.String())
	}

	return data, nil
}

// NewDifyResty 实例化dify实例
func NewDifyResty(baseUrl, token string) *resty.Client {
	client := resty.New()
	client.SetRetryCount(2).
		SetHeader("Content-Type", "application/json").
		SetBaseURL(baseUrl).
		SetHeader("Authorization", "Bearer "+token)

	return client
}
