import { f as defineAdminEventHandler, $ as getAuthRequestContext, q as readBody, c as createError, a0 as emitAdminBeforeLogin, a1 as verifyAdminCredentials, a2 as emitAdminLoginFailed, a3 as tryGetTenantContext, a4 as getDefaultTenantId, a5 as isMfaEnabledGlobally, a6 as getAdminMfaState, a7 as isMfaRequiredForRole, a8 as issueMfaChallenge, a9 as MFA_CHALLENGE_TTL_SECONDS, aa as generateAdminJWTForTenant, ab as emitAdminAfterLogin } from '../../../../nitro/nitro.mjs';
import 'node:crypto';
import 'jsonwebtoken';
import 'node:fs';
import 'node:module';
import 'node:path';
import 'node:url';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'pino';
import 'drizzle-orm/better-sqlite3';
import 'drizzle-orm/node-postgres';
import 'drizzle-orm/mysql2';
import 'better-sqlite3';
import 'pg';
import 'mysql2/promise';
import 'drizzle-orm';
import 'fs';
import 'path';
import 'prom-client';
import 'bcryptjs';
import '@node-rs/argon2';
import 'node:async_hooks';
import 'crypto';
import 'node:dns';
import 'node:util';
import 'node:net';
import 'fs/promises';
import 'url';
import 'semver';

const login_post = defineAdminEventHandler("admin:auth:login", async (event) => {
  var _a;
  const reqCtx = getAuthRequestContext(event);
  try {
    const body = await readBody(event);
    const { identifier, password } = body;
    if (!identifier || !password) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Email/username and password are required"
      });
    }
    await emitAdminBeforeLogin(identifier, reqCtx);
    const adminUser = await verifyAdminCredentials(identifier, password);
    if (!adminUser) {
      await emitAdminLoginFailed(identifier, "invalid_credentials", reqCtx);
      throw createError({
        statusCode: 401,
        statusMessage: "Unauthorized",
        message: "Invalid credentials"
      });
    }
    const tenant = tryGetTenantContext(event);
    const tenantId = (_a = tenant == null ? void 0 : tenant.id) != null ? _a : await getDefaultTenantId();
    const mfaActive = isMfaEnabledGlobally();
    const userMfa = mfaActive ? await getAdminMfaState(adminUser.id) : null;
    const enforced = mfaActive && isMfaRequiredForRole(adminUser.role);
    if (mfaActive && ((userMfa == null ? void 0 : userMfa.enabled) || enforced)) {
      const purpose = (userMfa == null ? void 0 : userMfa.enabled) ? "login" : "enroll";
      const challengeToken = issueMfaChallenge({
        sub: adminUser.id,
        username: adminUser.username,
        email: adminUser.email,
        role: adminUser.role,
        tid: tenantId,
        purpose,
        baseAmr: ["pwd"]
      });
      await emitAdminLoginFailed(identifier, "mfa_required", reqCtx);
      return {
        success: true,
        data: {
          mfaRequired: true,
          mfaPurpose: purpose,
          challengeToken,
          challengeExpiresIn: MFA_CHALLENGE_TTL_SECONDS
        }
      };
    }
    const tokenPayload = {
      id: adminUser.id,
      username: adminUser.username,
      email: adminUser.email,
      role: adminUser.role
    };
    const token = generateAdminJWTForTenant({ ...tokenPayload, amr: ["pwd"] }, tenantId);
    await emitAdminAfterLogin(
      adminUser.id,
      adminUser.email,
      adminUser.username,
      adminUser.role,
      reqCtx
    );
    const { getAdminScopesForRole } = await import('../../../../nitro/nitro.mjs').then(function (n) { return n.fc; });
    const adminScopes = await getAdminScopesForRole(adminUser.role);
    return {
      success: true,
      data: {
        token,
        user: {
          id: adminUser.id,
          username: adminUser.username,
          email: adminUser.email,
          firstName: adminUser.firstName,
          lastName: adminUser.lastName,
          role: adminUser.role,
          adminScopes
        }
      }
    };
  } catch (error) {
    if (error && typeof error === "object" && "statusCode" in error) {
      throw error;
    }
    console.error("[POST /api/admin/auth/login] Error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Login Failed",
      message: error instanceof Error ? error.message : "Unknown error"
    });
  }
});

export { login_post as default };
//# sourceMappingURL=login.post.mjs.map
