package corporate_services

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

type AccountService struct {
	AccountStore db.AppStore
}

func NewAccountService(aStore db.AppStore) *AccountService {
	return &AccountService{
		AccountStore: aStore,
	}
}

func (as *AccountService) ChangePasswordPIC(host string, token string, currPassword string, newPassword string) (models.ResponseStatus, error) {
	var ret models.ResponseStatus

	uri := "https://" + config.Data.Get("servername") + "/one-api/mockup/system/menu/change_password_pic"

	params := url.Values{}
	params.Add("new", newPassword)
	params.Add("old", currPassword)
	params.Add("token", token)

	req, err := http.PostForm(uri, params)
	if err != nil {
		ret = models.ResponseStatus{
			Status:  "ERR",
			Message: "error request change password",
		}
		return ret, err
	}
	defer req.Body.Close()

	resp, err := io.ReadAll(req.Body)
	if err != nil {
		ret = models.ResponseStatus{
			Status:  "ERR",
			Message: "error read response",
		}
		return ret, err
	}

	err = json.Unmarshal(resp, &ret)
	if err != nil {
		ret = models.ResponseStatus{
			Status:  "ERR",
			Message: "error unmarshal response",
		}
		return ret, err
	}

	return ret, nil
}

func (as *AccountService) ChangePasswordPAT(token string, currPassword string, newPassword string) (models.ResponseStatus, error) {
	var ret models.ResponseStatus

	uri := "https://" + config.Data.Get("servername") + "/one-api/mockup/system/menu/change_password_pat"

	params := url.Values{}
	params.Add("new", newPassword)
	params.Add("old", currPassword)
	params.Add("token", token)

	req, err := http.PostForm(uri, params)
	if err != nil {
		ret = models.ResponseStatus{
			Status:  "ERR",
			Message: "error request change password",
		}
		return ret, err
	}
	defer req.Body.Close()

	resp, err := io.ReadAll(req.Body)
	if err != nil {
		ret = models.ResponseStatus{
			Status:  "ERR",
			Message: "error read response",
		}
		return ret, err
	}

	err = json.Unmarshal(resp, &ret)
	if err != nil {
		ret = models.ResponseStatus{
			Status:  "ERR",
			Message: "error unmarshal response",
		}
		return ret, err
	}

	return ret, nil
}
