package client

import (
	"context"
	"fmt"
	"log"
	"net/url"

	"go.uber.org/zap"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/errors"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/utils"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/pkg/client"
)

type AuthClientDeps struct {
	Logger *zap.Logger
	URLs   *models.AuthMicroserviceURL
}

type AuthClient struct {
	urls *models.AuthMicroserviceURL
}

func NewAuthClient(deps AuthClientDeps) *AuthClient {
	if deps.URLs == nil {
		log.Panicln("urls is nil on <NewAuthClient>")
	}

	return &AuthClient{
		urls: deps.URLs,
	}
}

func (receiver *AuthClient) GetUser(ctx context.Context, userID string) (*models.User, errors.Error) {
	userURL, err := url.JoinPath(receiver.urls.User, userID)
	if err != nil {
		return nil, errors.New(
			fmt.Errorf("failed to join path on <GetUser> of <AuthClient>: %w", err),
			errors.ErrInternalError,
		)
	}

	response, err := client.Get[models.User, models.FastifyError](ctx, &client.RequestSettings{
		URL:     userURL,
		Headers: map[string]string{"Content-Type": "application/json"},
	})
	if err != nil {
		return nil, errors.New(
			fmt.Errorf("failed to request get user with <%s> on <GetUser> of <AuthClient>: %w", userID, err),
			errors.ErrInternalError,
		)
	}
	if response.Error != nil {
		return nil, errors.New(
			fmt.Errorf("failed request with <%s> on <GetUser> of <AuthClient>: %s", userID, response.Error.Message),
			utils.DetermineClientErrorResponse(response.StatusCode),
		)
	}

	return response.Body, nil
}
