package authflowv2

import (
	"context"
	"net/http"

	"net/url"

	handlerwebapp "github.com/authgear/authgear-server/pkg/auth/handler/webapp"
	"github.com/authgear/authgear-server/pkg/auth/handler/webapp/viewmodels"
	"github.com/authgear/authgear-server/pkg/auth/webapp"
	"github.com/authgear/authgear-server/pkg/lib/accountmanagement"
	"github.com/authgear/authgear-server/pkg/lib/session"
	"github.com/authgear/authgear-server/pkg/util/httproute"
	"github.com/authgear/authgear-server/pkg/util/template"
	"github.com/authgear/authgear-server/pkg/util/validation"
)

var TemplateWebSettingsIdentityAddEmailHTML = template.RegisterHTML(
	"web/authflowv2/settings_identity_add_email.html",
	handlerwebapp.SettingsComponents...,
)

var AuthflowV2SettingsIdentityAddEmailSchema = validation.NewSimpleSchema(`
	{
		"type": "object",
		"properties": {
			"x_login_id": { "type": "string" }
		},
		"required": ["x_login_id"]
	}
`)

func ConfigureAuthflowV2SettingsIdentityAddEmailRoute(route httproute.Route) httproute.Route {
	return route.
		WithMethods("OPTIONS", "POST", "GET").
		WithPathPattern(AuthflowV2RouteSettingsIdentityAddEmail)
}

type AuthflowV2SettingsIdentityAddEmailViewModel struct {
	LoginIDKey string
}

type AuthflowV2SettingsIdentityAddEmailHandler struct {
	ControllerFactory handlerwebapp.ControllerFactory
	BaseViewModel     *viewmodels.BaseViewModeler
	Renderer          handlerwebapp.Renderer
	AccountManagement accountmanagement.Service
}

func (h *AuthflowV2SettingsIdentityAddEmailHandler) GetData(r *http.Request, rw http.ResponseWriter) (map[string]interface{}, error) {
	data := map[string]interface{}{}

	loginIDKey := r.Form.Get("q_login_id_key")

	baseViewModel := h.BaseViewModel.ViewModel(r, rw)
	viewmodels.Embed(data, baseViewModel)

	vm := AuthflowV2SettingsIdentityAddEmailViewModel{
		LoginIDKey: loginIDKey,
	}
	viewmodels.Embed(data, vm)

	return data, nil
}

func (h *AuthflowV2SettingsIdentityAddEmailHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ctrl, err := h.ControllerFactory.New(r, w)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	defer ctrl.ServeWithoutDBTx(r.Context())

	ctrl.GetWithSettingsActionWebSession(r, func(ctx context.Context, _ *webapp.Session) error {
		data, err := h.GetData(r, w)
		if err != nil {
			return err
		}

		h.Renderer.RenderHTML(w, r, TemplateWebSettingsIdentityAddEmailHTML, data)
		return nil
	})

	ctrl.PostActionWithSettingsActionWebSession("", r, func(ctx context.Context, webappSession *webapp.Session) error {
		loginIDKey := r.Form.Get("q_login_id_key")

		err := AuthflowV2SettingsIdentityAddEmailSchema.Validator().ValidateValue(ctx, handlerwebapp.FormToJSON(r.Form))
		if err != nil {
			return err
		}

		loginID := r.Form.Get("x_login_id")

		s := session.GetSession(ctx)

		output, err := h.AccountManagement.StartAddIdentityEmail(ctx, s, &accountmanagement.StartAddIdentityEmailInput{
			LoginID:    loginID,
			LoginIDKey: loginIDKey,
		})
		if err != nil {
			return err
		}

		var redirectURI *url.URL
		navivagationAction := webapp.NavigationActionRedirect
		if output.NeedVerification {
			redirectURI, err = url.Parse(AuthflowV2RouteSettingsIdentityVerifyEmail)
			if err != nil {
				return err
			}

			q := redirectURI.Query()
			q.Set("q_login_id_key", loginIDKey)
			q.Set("q_token", output.Token)

			redirectURI.RawQuery = q.Encode()
			navivagationAction = webapp.NavigationActionAdvance
		} else if ctrl.IsInSettingsAction(s, webappSession) {
			settingsActionResult, err := ctrl.FinishSettingsActionWithResult(ctx, s, webappSession)
			if err != nil {
				return err
			}
			settingsActionResult.WriteResponse(w, r)
			return nil
		} else {
			redirectURI, err = url.Parse(AuthflowV2RouteSettingsIdentityListEmail)
			if err != nil {
				return err
			}

			q := redirectURI.Query()
			q.Set("q_login_id_key", loginIDKey)

			redirectURI.RawQuery = q.Encode()
		}

		result := webapp.Result{RedirectURI: redirectURI.String(), NavigationAction: navivagationAction}
		result.WriteResponse(w, r)
		return nil
	})
}
