package action

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"git.lxtend.com/lixiangwuxian/qqbot/config"
	"git.lxtend.com/lixiangwuxian/qqbot/constants"
	"git.lxtend.com/lixiangwuxian/qqbot/model"
)

func GetGroupMemberList(groupID int64) ([]model.GroupMember, error) {
	fullURL := fmt.Sprintf("http://%s%s?group_id=%d", config.ConfigManager.GetConfig().Management.NapcatHttpSrv, constants.GET_GROUP_MEMBER_LIST, groupID)

	response, err := http.Get(fullURL)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()

	body, err := io.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	var groupMemberListResponse model.GroupMemberListResponse
	err = json.Unmarshal(body, &groupMemberListResponse)
	if err != nil {
		return nil, err
	}

	return groupMemberListResponse.Data, nil
}

func GetGroupList() ([]model.Group, error) {
	fullURL := fmt.Sprintf("http://%s%s", config.ConfigManager.GetConfig().Management.NapcatHttpSrv, constants.GET_GROUP_LIST)

	response, err := http.Get(fullURL)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()

	body, err := io.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	var groupListResponse model.GroupListResponse
	err = json.Unmarshal(body, &groupListResponse)
	if err != nil {
		return nil, err
	}

	return groupListResponse.Data, nil
}

func GetLoginAccountInfo() (*model.LoginAccountInfoResponse, error) {
	fullURL := fmt.Sprintf("http://%s%s", config.ConfigManager.GetConfig().Management.NapcatHttpSrv, constants.GET_LOGIN_INFO)

	response, err := http.Post(fullURL, "application/json", nil)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()

	body, err := io.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	var loginAccountInfoResponse model.LoginAccountInfoResponse
	err = json.Unmarshal(body, &loginAccountInfoResponse)
	if err != nil {
		return nil, err
	}

	return &loginAccountInfoResponse, nil
}
