package pena_social_auth

import (
	"encoding/json"
	"fmt"
	"github.com/gofiber/fiber/v2"
	"go.uber.org/zap"
	"net/http"
)

type Deps struct {
	PenaSocialAuthURL string
	FiberClient       *fiber.Client
	Logger            *zap.Logger
	ReturnURL         string
}

type Client struct {
	penaSocialAuthURL string
	fiberClient       *fiber.Client
	logger            *zap.Logger
	returnURL         string
}

func NewClient(deps Deps) *Client {
	if deps.FiberClient == nil {
		deps.FiberClient = fiber.AcquireClient()
	}

	return &Client{
		penaSocialAuthURL: deps.PenaSocialAuthURL,
		fiberClient:       deps.FiberClient,
		returnURL:         deps.ReturnURL,
		logger:            deps.Logger,
	}
}

type GenAuthURLResp struct {
	URL string `json:"url"`
}

func (c *Client) GenerateAmocrmAuthURL(accountID string) (string, error) {
	url := c.penaSocialAuthURL + "?accessToken=" + accountID + "&returnUrl=" + c.returnURL
	statusCode, resp, errs := c.fiberClient.Get(url).Bytes()
	if len(errs) > 0 {
		for _, err := range errs {
			c.logger.Error("error sending request in GenerateAmocrmAuthURL", zap.Error(err))
		}
		return "", fmt.Errorf("request GenerateAmocrmAuthURL failed: %v", errs[0])
	}

	if statusCode != http.StatusOK {
		errorMessage := fmt.Sprintf("received an incorrect response from GenerateAmocrmAuthURL: %d", statusCode)
		c.logger.Error(errorMessage, zap.Int("status", statusCode))
		return "", fmt.Errorf(errorMessage)
	}

	var response GenAuthURLResp
	err := json.Unmarshal(resp, &response)
	if err != nil {
		c.logger.Error("error unmarshal GenAuthURLResp:", zap.Error(err))
		return "", err
	}

	return response.URL, nil
}
