package core

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/patrickmn/go-cache"
	"log"
	"os"
	"time"
)

const (
	sessionExpiration      = 5 * time.Minute
	sessionCleanupInterval = 10 * time.Minute
)

type NKodeAPI struct {
	Db                 DbAccessor
	SignupSessionCache *cache.Cache
	EmailQueue         *EmailQueue
}

func NewNKodeAPI(db DbAccessor, queue *EmailQueue) NKodeAPI {
	return NKodeAPI{
		Db:                 db,
		EmailQueue:         queue,
		SignupSessionCache: cache.New(sessionExpiration, sessionCleanupInterval),
	}
}

func (n *NKodeAPI) CreateNewCustomer(nkodePolicy NKodePolicy, id *CustomerId) (*CustomerId, error) {
	newCustomer, err := NewCustomer(nkodePolicy)
	if id != nil {
		newCustomer.Id = *id
	}
	if err != nil {
		return nil, err
	}
	err = n.Db.WriteNewCustomer(*newCustomer)

	if err != nil {
		return nil, err
	}
	return &newCustomer.Id, nil
}

func (n *NKodeAPI) GenerateSignupResetInterface(userEmail UserEmail, customerId CustomerId, kp KeypadDimension, reset bool) (*GenerateSignupResetInterfaceResp, error) {
	user, err := n.Db.GetUser(userEmail, customerId)
	if err != nil {
		return nil, err
	}
	if user != nil && !reset {
		log.Printf("user %s already exists", string(userEmail))
		return nil, ErrUserAlreadyExists
	}
	svgIdxInterface, err := n.Db.RandomSvgIdxInterface(kp)
	if err != nil {
		return nil, err
	}
	signupSession, err := NewSignupResetSession(userEmail, kp, customerId, svgIdxInterface, reset)
	if err != nil {
		return nil, err
	}
	//n.SignupSessions[signupSession.Id] = *signupSession
	if err := n.SignupSessionCache.Add(signupSession.Id.String(), *signupSession, sessionExpiration); err != nil {
		return nil, err
	}
	svgInterface, err := n.Db.GetSvgStringInterface(signupSession.LoginUserInterface.SvgId)

	if err != nil {
		return nil, err
	}
	resp := GenerateSignupResetInterfaceResp{
		UserIdxInterface: signupSession.SetIdxInterface,
		SvgInterface:     svgInterface,
		SessionId:        uuid.UUID(signupSession.Id).String(),
		Colors:           signupSession.Colors,
	}
	return &resp, nil
}

func (n *NKodeAPI) SetNKode(customerId CustomerId, sessionId SessionId, keySelection KeySelection) (IdxInterface, error) {
	_, err := n.Db.GetCustomer(customerId)

	if err != nil {
		return nil, err
	}
	session, exists := n.SignupSessionCache.Get(sessionId.String())
	if !exists {
		log.Printf("session id does not exist %s", sessionId)
		return nil, ErrSignupSessionDNE
	}
	userSession, ok := session.(UserSignSession)
	if !ok {
		// handle the case where the type assertion fails
		return nil, ErrSignupSessionDNE
	}
	confirmInterface, err := userSession.SetUserNKode(keySelection)
	if err != nil {
		return nil, err
	}
	n.SignupSessionCache.Set(sessionId.String(), userSession, sessionExpiration)
	return confirmInterface, nil
}

func (n *NKodeAPI) ConfirmNKode(customerId CustomerId, sessionId SessionId, keySelection KeySelection) error {
	session, exists := n.SignupSessionCache.Get(sessionId.String())
	if !exists {
		log.Printf("session id does not exist %s", sessionId)
		return ErrSignupSessionDNE
	}
	userSession, ok := session.(UserSignSession)
	if !ok {
		// handle the case where the type assertion fails
		return ErrSignupSessionDNE
	}
	customer, err := n.Db.GetCustomer(customerId)
	if err != nil {
		return err
	}
	passcode, err := userSession.DeducePasscode(keySelection)
	if err != nil {
		return err
	}
	if err = customer.IsValidNKode(userSession.Kp, passcode); err != nil {
		return err
	}
	user, err := NewUser(*customer, string(userSession.UserEmail), passcode, userSession.LoginUserInterface, userSession.Kp)
	if err != nil {
		return err
	}
	if userSession.Reset {
		err = n.Db.UpdateUserNKode(*user)
	} else {
		err = n.Db.WriteNewUser(*user)
	}
	n.SignupSessionCache.Delete(userSession.Id.String())
	return err
}

func (n *NKodeAPI) GetLoginInterface(userEmail UserEmail, customerId CustomerId) (*GetLoginInterfaceResp, error) {
	user, err := n.Db.GetUser(userEmail, customerId)
	if err != nil {
		return nil, err
	}
	if user == nil {
		log.Printf("user %s for customer %s dne", userEmail, customerId)
		return nil, ErrUserForCustomerDNE
	}
	err = user.Interface.PartialInterfaceShuffle()
	if err != nil {
		return nil, err
	}
	err = n.Db.UpdateUserInterface(user.Id, user.Interface)
	if err != nil {
		return nil, err
	}
	svgInterface, err := n.Db.GetSvgStringInterface(user.Interface.SvgId)
	if err != nil {
		return nil, err
	}
	resp := GetLoginInterfaceResp{
		UserIdxInterface: user.Interface.IdxInterface,
		SvgInterface:     svgInterface,
		NumbOfKeys:       user.Kp.NumbOfKeys,
		AttrsPerKey:      user.Kp.AttrsPerKey,
		Colors:           SetColors,
	}
	return &resp, nil
}

func (n *NKodeAPI) Login(customerId CustomerId, userEmail UserEmail, keySelection KeySelection) (*AuthenticationTokens, error) {
	customer, err := n.Db.GetCustomer(customerId)
	if err != nil {
		return nil, err
	}
	user, err := n.Db.GetUser(userEmail, customerId)
	if err != nil {
		return nil, err
	}
	if user == nil {
		log.Printf("user %s for customer %s dne", userEmail, customerId)
		return nil, ErrUserForCustomerDNE
	}
	passcode, err := ValidKeyEntry(*user, *customer, keySelection)
	if err != nil {
		return nil, err
	}

	if user.Renew {
		err = n.Db.RefreshUserPasscode(*user, passcode, customer.Attributes)
		if err != nil {
			return nil, err
		}
	}
	jwtToken, err := NewAuthenticationTokens(string(user.Email), customerId)
	if err != nil {
		return nil, err
	}
	err = n.Db.UpdateUserRefreshToken(user.Id, jwtToken.RefreshToken)
	if err != nil {
		return nil, err
	}
	return &jwtToken, nil
}

func (n *NKodeAPI) RenewAttributes(customerId CustomerId) error {
	return n.Db.Renew(customerId)
}

func (n *NKodeAPI) RandomSvgInterface() ([]string, error) {
	return n.Db.RandomSvgInterface(KeypadMax)
}

func (n *NKodeAPI) RefreshToken(userEmail UserEmail, customerId CustomerId, refreshToken string) (string, error) {
	user, err := n.Db.GetUser(userEmail, customerId)
	if err != nil {
		return "", err
	}
	if user == nil {
		log.Printf("user %s for customer %s dne", userEmail, customerId)
		return "", ErrUserForCustomerDNE
	}
	if user.RefreshToken != refreshToken {
		return "", ErrRefreshTokenInvalid
	}
	refreshClaims, err := ParseRegisteredClaimToken(refreshToken)
	if err != nil {
		return "", err
	}
	if err = ClaimExpired(*refreshClaims); err != nil {
		return "", err
	}
	newAccessClaims := NewAccessClaim(string(userEmail), customerId)
	return EncodeAndSignClaims(newAccessClaims)
}

func (n *NKodeAPI) ResetNKode(userEmail UserEmail, customerId CustomerId) error {
	user, err := n.Db.GetUser(userEmail, customerId)
	if err != nil {
		return fmt.Errorf("error getting user in rest nkode %v", err)
	}

	if user == nil {
		return nil
	}

	nkodeResetJwt, err := ResetNKodeToken(userEmail, customerId)
	if err != nil {
		return err
	}
	frontendHost := os.Getenv("FRONTEND_HOST")
	if frontendHost == "" {
		frontendHost = FrontendHost
	}
	htmlBody := fmt.Sprintf("<h1>Hello!</h1><p>Click the link to reset your nKode.</p><a href=\"%s?token=%s\">Reset nKode</a>", frontendHost, nkodeResetJwt)
	email := Email{
		Sender:    "no-reply@nkode.tech",
		Recipient: string(userEmail),
		Subject:   "nKode Reset",
		Content:   htmlBody,
	}
	n.EmailQueue.AddEmail(email)
	return nil
}
