package server

import (
	"fmt"
	d "playback-device-server/data"
	m "playback-device-server/management"
	"strings"

	"github.com/labstack/echo/v4"
	"github.com/rs/zerolog/log"
)

type AuthContext struct {
	echo.Context
	User        *d.User
	Session     *d.UserSession
	Integration *d.Integration
}

type Authenticator struct {
	userManager   *m.UserManager
	deviceManager *m.DeviceManager
}

func (r *Authenticator) SetUserManager(userManager *m.UserManager) {
	r.userManager = userManager
}

func (r *Authenticator) SetDeviceManager(deviceManager *m.DeviceManager) {
	r.deviceManager = deviceManager
}

func (r *Authenticator) Authenticate(path string, exceptions []string) func(next echo.HandlerFunc) echo.HandlerFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(context echo.Context) error {
			requestURI := context.Request().RequestURI
			if !strings.HasPrefix(requestURI, path) {
				return next(context)
			}
			for _, exception := range exceptions {
				if strings.HasPrefix(requestURI, exception) {
					return next(context)
				}
			}
			cookie, err := context.Cookie("token")
			if err != nil {
				SendError(401, context, "no cookie for session token found")
				return err
			}
			token := cookie.Value
			user, session, error := r.getUserAndSession(token)
			if error != nil {
				log.Error().Err(error).Msg("error authenticating user")
				SendError(500, context, fmt.Sprintf("error authenticating user: %s", error))
				return error
			}

			integration, error := r.getIntegration(token)
			if error != nil {
				log.Error().Err(error).Msg("error getting integration")
				SendError(500, context, fmt.Sprintf("error getting integration: %s", error))
				return error
			}

			if integration == nil && user == nil {
				log.Error().Msg("no integration or user found for given token")
				SendError(401, context, "no integration or user found for given token")
				return fmt.Errorf("no integration or user found for given token")
			}

			authContext := AuthContext{Context: context, User: user, Session: session, Integration: integration}

			return next(authContext)
		}
	}
}

func (r *Authenticator) getUserAndSession(token string) (*d.User, *d.UserSession, error) {
	session, error := r.userManager.GetSession(token)
	if error != nil {
		return nil, nil, error
	}
	if session == nil {
		return nil, nil, nil
	}

	user, error := r.userManager.GetUserById(session.UserID)
	if error != nil {
		return nil, nil, error
	}
	return user, session, nil
}

func (r *Authenticator) getIntegration(token string) (*d.Integration, error) {
	integration, error := r.deviceManager.GetIntegrationByToken(token)
	if error != nil {
		return nil, error
	}
	return integration, nil
}
