package client

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

	"gitea.pena/PenaSide/customer/internal/errors"
	"gitea.pena/PenaSide/customer/internal/models"
	"gitea.pena/PenaSide/customer/internal/utils"
	"gitea.pena/PenaSide/customer/pkg/client"
	"go.uber.org/zap"
)

type AuthClientDeps struct {
	Logger *zap.Logger
	URL    string
}

type AuthClient struct {
	url string
}

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

	return &AuthClient{
		url: deps.URL,
	}
}

func (receiver *AuthClient) GetUser(ctx context.Context, userID string) (*models.User, errors.Error) {
	userURL, err := url.JoinPath(fmt.Sprintf("%s/user", receiver.url), 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
}
