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 HubadminClientDeps struct {
	Logger *zap.Logger
	URL    string
}

type HubadminClient struct {
	logger *zap.Logger
	url    string
}

func NewHubadminClient(deps HubadminClientDeps) *HubadminClient {
	if deps.Logger == nil {
		log.Panicln("logger is nil on <NewHubadminClient>")
	}

	if deps.URL == "" {
		log.Panicln("urls is nil on <NewHubadminClient>")
	}

	return &HubadminClient{
		logger: deps.Logger,
		url:    deps.URL,
	}
}

func (receiver *HubadminClient) GetTariff(ctx context.Context, accessToken string, tariffID string) (*models.Tariff, errors.Error) {
	tariffURL, err := url.JoinPath(fmt.Sprintf("%s/tariff", receiver.url), tariffID)
	if err != nil {
		return nil, errors.New(fmt.Errorf("failed to join path on <GetTariff> of <HubadminClient>: %w", err), errors.ErrInternalError)
	}

	response, err := client.Get[models.Tariff, models.FastifyError](ctx, &client.RequestSettings{
		URL: tariffURL,
		Headers: map[string]string{
			"Content-Type":  "application/json",
			"Authorization": fmt.Sprintf("Bearer %s", accessToken),
		},
	})
	if err != nil {
		receiver.logger.Error("failed to request get tariff on <GetTariff> of <HubadminClient>",
			zap.Error(err),
			zap.String("tariffID", tariffID),
		)

		return nil, errors.New(
			fmt.Errorf("failed to request get tariff with <%s> on <GetTariff> of <HubadminClient>: %w", tariffID, err),
			errors.ErrInternalError,
		)
	}
	if response.Error != nil {
		receiver.logger.Error("failed request on <GetTariff> of <HubadminClient>",
			zap.String("error", response.Error.Message),
			zap.String("tariffID", tariffID),
		)

		return nil, errors.New(
			fmt.Errorf("failed request with <%s> on <GetTariff> of <HubadminClient>: %s", tariffID, response.Error.Message),
			utils.DetermineClientErrorResponse(response.StatusCode),
		)
	}

	return response.Body, nil
}

func (receiver *HubadminClient) GetTariffs(ctx context.Context, accessToken string, tarriffIDs []string) ([]models.Tariff, errors.Error) {
	tariffs := make([]models.Tariff, len(tarriffIDs))

	for index, tariffID := range tarriffIDs {
		tariff, err := receiver.GetTariff(ctx, accessToken, tariffID)
		if err != nil {
			receiver.logger.Error("failed to get tariff on <GetTariffs> of <HubadminClient>", zap.Error(err), zap.String("tariffID", tariffID))
			return []models.Tariff{}, err
		}

		tariffs[index] = *tariff
	}

	return tariffs, nil
}
