package client

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

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

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

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

func NewVerificationClient(deps VerificationClientDeps) *VerificationClient {
	if deps.Logger == nil {
		log.Panicln("logger is nil on <NewVerificationClient>")
	}

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

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

func (receiver *VerificationClient) GetVerification(ctx context.Context, token, userID string) (*models.Verification, errors.Error) {
	verifURL, err := url.JoinPath(fmt.Sprintf("%s/verification", receiver.url), userID)
	if err != nil {
		return nil, errors.New(
			fmt.Errorf("failed to join path on <GetVerification> of <VerificationClient>: %w", err),
			errors.ErrInternalError,
		)
	}

	response, err := client.Get[models.Verification, models.FastifyError](ctx, &client.RequestSettings{
		URL: verifURL,
		Headers: map[string]string{
			"Content-Type":  "application/json",
			"Authorization": token,
		},
	})
	if err != nil {
		if response != nil {
			if response.StatusCode == 404 {
				return &models.Verification{}, nil
			}
		}
		return nil, errors.New(err, errors.ErrInternalError)
	}

	return response.Body, nil
}
