package service

import (
	"context"
	"fmt"
	"time"

	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)

type Config struct {
	LengthOfOtpCode int           `koanf:"length_of_otp_code"`
	OtpChars        string        `koanf:"otp_chars"`
	OtpExpireTime   time.Duration `koanf:"otp_expire_time"`
}

type AccountClient interface {
	SendOTP(ctx context.Context, phoneNumber string) error
	LoginOrRegister(ctx context.Context, req LoginOrRegisterRequest) (LoginOrRegisterResponse, error)
}

type AuthClient interface {
	CreateAccessToken()
	CreateRefreshToken()
}

type Service struct {
	config        Config
	accountClient AccountClient
	validator     Validator
}

func NewService(cfg Config,
	accountClient AccountClient,
	validator Validator) Service {
	return Service{
		config:        cfg,
		accountClient: accountClient,
		validator:     validator,
	}
}

func (s Service) SendOtp(ctx context.Context, req SendOtpRequest) (SendOtpResponse, error) {
	const op = "driverService.SendOtp"
	err := s.validator.ValidateSendOtpRequest(req)
	if err != nil {
		return SendOtpResponse{}, richerror.New(op).WithErr(err).WithMessage(err.Error())
	}

	sErr := s.accountClient.SendOTP(ctx, req.PhoneNumber)
	if sErr != nil {
		return SendOtpResponse{}, richerror.New(op).WithErr(sErr).WithMessage(sErr.Error())
	}

	return SendOtpResponse{}, nil
}

func (s Service) LoginOrRegister(ctx context.Context, req LoginOrRegisterRequest) (LoginOrRegisterResponse, error) {
	const op = "driverService.LoginOrRegister"

	err := s.validator.ValidateLoginOrRegisterRequest(req)
	if err != nil {
		return LoginOrRegisterResponse{}, richerror.New(op).WithErr(err).WithMessage(err.Error())
	}

	resp, lErr := s.accountClient.LoginOrRegister(ctx, req)
	if lErr != nil {
		return LoginOrRegisterResponse{}, err
	}

	fmt.Println("res:", resp)

	// TODO : CreateAccessToken and create CreateRefreshToken

	return LoginOrRegisterResponse{}, nil
}
