package auth

import (
	"fmt"
	"github.com/gofiber/fiber/v2"
	"log"
)

type IAuthClient interface {
	GetUserEmail(userID string) (string, error)
}

type AuthClient struct {
	URL string
}

type User struct {
	Email string `json:"login"`
}

func NewAuthClient(url string) *AuthClient {
	if url == "" {
		log.Panicln("url is nil on <NewAuthClient>")
	}

	return &AuthClient{
		URL: url,
	}
}

func (client *AuthClient) GetUserEmail(userID string) (string, error) {
	fiberClient := fiber.Client{}

	userURL := fmt.Sprintf("%s/%s", client.URL, userID)

	var user User
	status, resp, errs := fiberClient.Get(userURL).Struct(&user)

	if len(errs) > 0 {
		return "", errs[0]
	}

	if status != fiber.StatusOK {
		return "", fmt.Errorf("unexpected status code: %d, user: %s, reesponse: %s", status, userID, string(resp))
	}

	return user.Email, nil
}

type MockAuthClient struct{}

func (m *MockAuthClient) GetUserEmail(userID string) (string, error) {
	return "test@example.com", nil
}
