package api

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/patrickmn/go-cache"
	"go-nkode/config"
	"go-nkode/internal/email"
	"go-nkode/internal/entities"
	"go-nkode/internal/models"
	"go-nkode/internal/repository"
	"go-nkode/internal/security"
	"log"
	"os"
	"time"
)

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

type NKodeAPI struct {
	Db                 repository.CustomerUserRepository
	SignupSessionCache *cache.Cache
	EmailQueue         *email.Queue
}

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

func (n *NKodeAPI) CreateNewCustomer(nkodePolicy models.NKodePolicy, id *models.CustomerID) (*models.CustomerID, error) {
	newCustomer, err := entities.NewCustomer(nkodePolicy)
	if id != nil {
		newCustomer.ID = *id
	}
	if err != nil {
		return nil, err
	}
	err = n.Db.CreateCustomer(*newCustomer)
	if err != nil {
		return nil, err
	}
	return &newCustomer.ID, nil
}

func (n *NKodeAPI) GenerateSignupResetInterface(userEmail models.UserEmail, customerId models.CustomerID, kp entities.KeypadDimension, reset bool) (*models.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, config.ErrUserAlreadyExists
	}
	//svgIdxInterface, err := n.Db.RandomSvgIdxInterface(kp)
	//if err != nil {
	//	return nil, err
	//}
	svgIdxInterface := make(models.SvgIdInterface, 54)
	for idx := range 54 {
		svgIdxInterface[idx] = idx + 1
	}
	signupSession, err := entities.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 := models.GenerateSignupResetInterfaceResp{
		UserIdxInterface: signupSession.SetIdxInterface,
		SvgInterface:     svgInterface,
		SessionId:        uuid.UUID(signupSession.Id).String(),
		Colors:           signupSession.Colors,
	}
	return &resp, nil
}

func (n *NKodeAPI) GenerateSignupResetInterfaceRigged(userEmail models.UserEmail, customerId models.CustomerID, kp entities.KeypadDimension, reset bool) (*models.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, config.ErrUserAlreadyExists
	}
	svgIdxInterface := make(models.SvgIdInterface, kp.TotalAttrs())
	for idx := range kp.TotalAttrs() {
		svgIdxInterface[idx] = idx
	}
	signupSession, err := entities.NewSignupResetSessionRigged(userEmail, kp, customerId, svgIdxInterface, reset)
	if err != nil {
		return nil, err
	}
	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 := models.GenerateSignupResetInterfaceResp{
		UserIdxInterface: signupSession.SetIdxInterface,
		SvgInterface:     svgInterface,
		SessionId:        uuid.UUID(signupSession.Id).String(),
		Colors:           signupSession.Colors,
	}
	return &resp, nil
}

func (n *NKodeAPI) SetNKode(customerId models.CustomerID, sessionId models.SessionId, keySelection models.KeySelection) (models.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, config.ErrSignupSessionDNE
	}
	userSession, ok := session.(entities.UserSignSession)
	if !ok {
		// handle the case where the type assertion fails
		return nil, config.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 models.CustomerID, sessionId models.SessionId, keySelection models.KeySelection) error {
	session, exists := n.SignupSessionCache.Get(sessionId.String())
	if !exists {
		log.Printf("session id does not exist %s", sessionId)
		return config.ErrSignupSessionDNE
	}
	userSession, ok := session.(entities.UserSignSession)
	if !ok {
		// handle the case where the type assertion fails
		return config.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 := entities.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 models.UserEmail, customerId models.CustomerID) (*models.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, config.ErrUserForCustomerDNE
	}
	svgInterface, err := n.Db.GetSvgStringInterface(user.Interface.SvgId)
	if err != nil {
		return nil, err
	}
	resp := models.GetLoginInterfaceResp{
		UserIdxInterface: user.Interface.IdxInterface,
		SvgInterface:     svgInterface,
		NumbOfKeys:       user.Kp.NumbOfKeys,
		AttrsPerKey:      user.Kp.AttrsPerKey,
		Colors:           models.SetColors,
	}
	return &resp, nil
}

func (n *NKodeAPI) Login(customerId models.CustomerID, userEmail models.UserEmail, keySelection models.KeySelection) (*security.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, config.ErrUserForCustomerDNE
	}
	passcode, err := entities.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 := security.NewAuthenticationTokens(string(user.Email), uuid.UUID(customerId))
	if err != nil {
		return nil, err
	}
	if err = n.Db.UpdateUserRefreshToken(user.Id, jwtToken.RefreshToken); err != nil {
		return nil, err
	}
	if err = user.Interface.LoginShuffle(); err != nil {
		return nil, err
	}
	if err = n.Db.UpdateUserInterface(user.Id, user.Interface); err != nil {
		return nil, err
	}
	return &jwtToken, nil
}

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

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

func (n *NKodeAPI) RefreshToken(userEmail models.UserEmail, customerId models.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 "", config.ErrUserForCustomerDNE
	}
	if user.RefreshToken != refreshToken {
		return "", config.ErrRefreshTokenInvalid
	}
	refreshClaims, err := security.ParseRegisteredClaimToken(refreshToken)
	if err != nil {
		return "", err
	}
	if err = security.ClaimExpired(*refreshClaims); err != nil {
		return "", err
	}
	newAccessClaims := security.NewAccessClaim(string(userEmail), uuid.UUID(customerId))
	return security.EncodeAndSignClaims(newAccessClaims)
}

func (n *NKodeAPI) ResetNKode(userEmail models.UserEmail, customerId models.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 := security.ResetNKodeToken(string(userEmail), uuid.UUID(customerId))
	if err != nil {
		return err
	}
	frontendHost := os.Getenv("FRONTEND_HOST")
	if frontendHost == "" {
		frontendHost = config.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)
	emailData := email.Email{
		Sender:    "no-reply@nkode.tech",
		Recipient: string(userEmail),
		Subject:   "nKode Reset",
		Content:   htmlBody,
	}
	n.EmailQueue.AddEmail(emailData)
	return nil
}
