import { d as defineEventHandler, $ as getAuthRequestContext, q as readBody, c as createError, dx as emitAuthBeforeLogin, G as createContentManager, dy as emitAuthLoginFailed, dz as verifyPassword, dA as hashPassword, du as generateJWT, dB as emitAuthAfterLogin } 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 = defineEventHandler(async (event) => {
  const reqCtx = getAuthRequestContext(event);
  try {
    const body = await readBody(event);
    if (!body || typeof body !== "object") {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Request body must be a valid JSON object"
      });
    }
    const { identifier, password } = body;
    if (!identifier || !password) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Email/username and password are required"
      });
    }
    await emitAuthBeforeLogin(identifier, reqCtx);
    const userManager = createContentManager("user");
    let user = null;
    const usersByEmail = await userManager.findMany({
      filters: { email: identifier },
      limit: 1,
      populate: "role"
    });
    if (usersByEmail.data.length > 0) {
      user = usersByEmail.data[0];
    } else {
      const usersByUsername = await userManager.findMany({
        filters: { username: identifier },
        limit: 1,
        populate: "role"
      });
      if (usersByUsername.data.length > 0) {
        user = usersByUsername.data[0];
      }
    }
    if (!user) {
      await emitAuthLoginFailed(identifier, "user_not_found", reqCtx);
      throw createError({
        statusCode: 401,
        statusMessage: "Unauthorized",
        message: "Invalid credentials"
      });
    }
    if (user.blocked) {
      await emitAuthLoginFailed(identifier, "user_blocked", reqCtx);
      throw createError({
        statusCode: 403,
        statusMessage: "Forbidden",
        message: "Your account has been blocked. Please contact support."
      });
    }
    const passwordVerification = await verifyPassword(password, user.password);
    if (!passwordVerification.valid) {
      await emitAuthLoginFailed(identifier, "invalid_credentials", reqCtx);
      throw createError({
        statusCode: 401,
        statusMessage: "Unauthorized",
        message: "Invalid credentials"
      });
    }
    if (passwordVerification.needsRehash) {
      try {
        await userManager.update(Number(user.id), {
          password: await hashPassword(password)
        });
      } catch (error) {
        console.warn("[auth] Failed to rehash legacy content user password after login:", error);
      }
    }
    const roleObj = user.role;
    const roleName = (roleObj == null ? void 0 : roleObj.name) || "authenticated";
    const jwtPayload = {
      id: user.id,
      username: user.username,
      email: user.email,
      role: roleName
    };
    const token = generateJWT(jwtPayload);
    const { password: _, ...userWithoutPassword } = user;
    await emitAuthAfterLogin(
      jwtPayload.id,
      jwtPayload.email,
      jwtPayload.username,
      jwtPayload.role,
      reqCtx
    );
    return {
      success: true,
      message: "Login successful",
      data: {
        user: userWithoutPassword,
        token
      }
    };
  } catch (error) {
    if (error instanceof Error && error.message.includes("Schema") && error.message.includes("not found")) {
      throw createError({
        statusCode: 500,
        statusMessage: "Configuration Error",
        message: "User schema is not configured. Please run database sync."
      });
    }
    if (error && typeof error === "object" && "statusCode" in error) {
      throw error;
    }
    console.error("[POST /api/auth/login] Error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Login Failed",
      message: error instanceof Error ? error.message : "Unknown error occurred"
    });
  }
});

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