package public_services

import (
	"cpone/db"
	"cpone/models"
	"cpone/package/config"
	"encoding/json"
	"io"
	"net/http"
	"net/url"

	"go.uber.org/zap"
)

type ServicesLogin struct {
	CompanyStore db.AppStore
}

func NewServicesLogin(uStore db.AppStore) *ServicesLogin {

	return &ServicesLogin{
		CompanyStore: uStore,
	}
}

func (ls *ServicesLogin) MultiSignIn(username string, password string, host string) (models.Response, error) {
	logger, _ := zap.NewProduction()
	var ret models.Response

	uri := "https://" + config.Data.Get("servername") + "/one-api/v1/system/auth/multi_login"

	params := url.Values{}
	params.Add("username", username)
	params.Add("password", password)

	resp, err := http.PostForm(uri, params)
	if err != nil {
		defer logger.Sync()
		logger.Error("error request post", zap.Any("error", err))
		return ret, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		defer logger.Sync()
		logger.Error("error read body", zap.Any("error", err))
		return ret, err
	}

	err = json.Unmarshal(body, &ret)
	if err != nil {
		defer logger.Sync()
		logger.Error("error parse body", zap.Any("error", err))
		return ret, err
	}

	return ret, nil
}
