// Copyright 2026 Moko Consulting <hello@mokoconsulting.tech>
// SPDX-License-Identifier: GPL-3.0-or-later

package org

import (
	auth_model "code.mokoconsulting.tech/MokoConsulting/MokoGitea/models/auth"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/setting"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/services/context"
)

// Check2FARequirement checks if the current org requires 2FA and if the user has it enabled.
// If the user doesn't have 2FA and the org requires it, redirect to 2FA setup page.
func Check2FARequirement(ctx *context.Context) {
	if ctx.Org == nil || ctx.Org.Organization == nil || ctx.Doer == nil {
		return
	}

	if !ctx.Org.Organization.Require2FA {
		return
	}

	// Check if user has 2FA enabled
	has, err := auth_model.HasTwoFactorOrWebAuthn(ctx, ctx.Doer.ID)
	if err != nil {
		ctx.ServerError("HasTwoFactorOrWebAuthn", err)
		return
	}

	if has {
		return
	}

	// User doesn't have 2FA — show warning and redirect to settings
	ctx.Flash.Warning("This organization requires two-factor authentication. Please enable 2FA to continue.")
	ctx.Redirect(setting.AppSubURL + "/user/settings/security")
}
