import { Router } from "express";
import bcrypt from "bcryptjs";
import rateLimit from "express-rate-limit";
import { z } from "zod";
import { prisma } from "../prisma.js";
import { signAccessToken, signPending2FAToken, verifyPending2FAToken, verifyPasswordResetToken } from "../auth/jwt.js";
import { issueEmailChallengeAndSend, verifyEmailChallenge } from "../services/twoFactor.js";
import { EMAIL_2FA_ENABLED_KEY, getBoolSetting } from "../services/appSettings.js";
import { clearLoginFailures, getRemainingLockoutSeconds, recordFailedLoginAttempt } from "../services/loginLockout.js";
import { writeAuditEvent } from "../services/auditEventService.js";
import { requireAuth, type AuthedRequest } from "../middleware/auth.js";
import { canUserAuthenticate } from "../services/userAccessPolicy.js";

const router = Router();

const loginSchema = z.object({
  // Trimmed, lower-cased and length-capped before the lookup so a huge or padded
  // payload can never reach the user query / bcrypt comparison.
  email: z
    .string({ required_error: "Email is required.", invalid_type_error: "Email must be text." })
    .trim()
    .toLowerCase()
    .max(254, "Email address is too long.")
    .refine((v) => /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/.test(v), "Enter a valid email address."),
  password: z
    .string({ required_error: "Password is required.", invalid_type_error: "Password must be text." })
    .min(1, "Password is required.")
    .max(256, "Password is too long."),
});

const verifySchema = z.object({
  pendingToken: z.string().min(1).max(2048),
  code: z.string().regex(/^[0-9]{6}$/, "Code must be 6 digits"),
});

const resendSchema = z.object({
  pendingToken: z.string().min(1).max(2048),
});
const changePasswordRequiredSchema = z.object({
  newPassword: z.string().min(10).max(255),
  confirmPassword: z.string().min(10).max(255),
});
const changePasswordSchema = z.object({
  currentPassword: z.string().min(1),
  newPassword: z.string().min(10).max(255),
  confirmPassword: z.string().min(10).max(255),
});
const resetPasswordWithTokenSchema = z.object({
  token: z.string().min(1).max(2048),
  newPassword: z.string().min(10).max(255),
  confirmPassword: z.string().min(10).max(255),
});

function clientIp(req: { ip?: string; socket: { remoteAddress?: string } }): string | undefined {
  return req.ip || req.socket?.remoteAddress;
}

const loginLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 20,
  standardHeaders: true,
  legacyHeaders: false,
});

const resendLimiter = rateLimit({
  windowMs: 60 * 1000,
  max: 3,
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: "Too many resend requests. Try again shortly." },
});

async function appendLockoutAuditEvent(userId: bigint, email: string, remainingSeconds: number) {
  const membership = await prisma.projectUser.findFirst({
    where: { userId },
    select: { projectId: true },
    orderBy: { id: "asc" },
  });
  if (!membership) return;
  await writeAuditEvent({
    projectId: membership.projectId,
    module: "users",
    action: "login_lockout_triggered",
    sourceType: "auth_login",
    sourceRef: email.toLowerCase().trim(),
    payloadRaw: JSON.stringify({ remainingSeconds }),
    meta: { remainingSeconds },
    actorUserId: userId,
  });
}

router.post("/login", loginLimiter, async (req, res) => {
  const parsed = loginSchema.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    return;
  }
  const { email, password } = parsed.data;

  const user = await prisma.user.findUnique({
    where: { email: email.toLowerCase().trim() },
    select: {
      id: true,
      name: true,
      email: true,
      password: true,
      mustChangePassword: true,
      lockedUntil: true,
    },
  });
  if (user?.lockedUntil && user.lockedUntil.getTime() > Date.now()) {
    const remainingSeconds = getRemainingLockoutSeconds(user.lockedUntil);
    res.status(423).json({
      error: "Account temporarily locked due to repeated failed login attempts.",
      code: "ACCOUNT_LOCKED",
      remainingSeconds,
    });
    return;
  }
  if (!user || !(await bcrypt.compare(password, user.password))) {
    if (user) {
      const lockout = await recordFailedLoginAttempt(prisma, user.id);
      if (lockout.locked) {
        await appendLockoutAuditEvent(user.id, email, lockout.remainingSeconds);
        res.status(423).json({
          error: "Account temporarily locked due to repeated failed login attempts.",
          code: "ACCOUNT_LOCKED",
          remainingSeconds: lockout.remainingSeconds,
        });
        return;
      }
    }
    res.status(401).json({ error: "Invalid email or password" });
    return;
  }
  await clearLoginFailures(prisma, user.id);

  if (!(await canUserAuthenticate(prisma, user.id))) {
    res.status(403).json({
      error: "Your account access has been deactivated. Contact your training provider administrator.",
      code: "ACCOUNT_DEACTIVATED",
    });
    return;
  }

  // Align with Laravel: ONLY the global admin setting controls whether email 2FA is enforced.
  const globallyEnabled = await getBoolSetting(prisma, EMAIL_2FA_ENABLED_KEY, false);
  if (!globallyEnabled) {
    const accessToken = signAccessToken(Number(user.id), user.email);
    res.json({
      requiresTwoFactor: false,
      accessToken,
      requiresPasswordChange: user.mustChangePassword,
      user: { id: Number(user.id), name: user.name, email: user.email },
    });
    return;
  }

  try {
    await issueEmailChallengeAndSend(prisma, user.id, user.email, clientIp(req));
  } catch (e) {
    const detail = e instanceof Error ? e.message : "unknown smtp error";
    console.error("[auth/login] failed to send 2FA code:", detail);
    res.status(503).json({
      error: "Could not send verification code. Check MAIL_MODE/SMTP settings or server logs.",
      ...(process.env.NODE_ENV !== "production" ? { detail } : {}),
    });
    return;
  }

  const pendingToken = signPending2FAToken(Number(user.id), user.email);
  res.json({
    requiresTwoFactor: true,
    pendingToken,
    maskedEmail: maskEmail(user.email),
  });
});

router.post("/verify-2fa", loginLimiter, async (req, res) => {
  const parsed = verifySchema.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    return;
  }
  let payload;
  try {
    payload = verifyPending2FAToken(parsed.data.pendingToken);
  } catch {
    res.status(401).json({ error: "Invalid or expired session. Please sign in again." });
    return;
  }

  const globallyEnabled = await getBoolSetting(prisma, EMAIL_2FA_ENABLED_KEY, false);
  if (!globallyEnabled) {
    res.status(409).json({ error: "Two-factor authentication is currently disabled by admin settings." });
    return;
  }

  const result = await verifyEmailChallenge(prisma, BigInt(payload.sub), parsed.data.code);
  if (!result.ok) {
    const msg =
      result.reason === "invalid"
        ? "Incorrect verification code."
        : result.reason === "none"
          ? "No active code. Request a new one."
          : "Verification code expired.";
    res.status(422).json({ error: msg });
    return;
  }

  const user = await prisma.user.findUnique({
    where: { id: BigInt(payload.sub) },
    select: { id: true, name: true, email: true, password: true, mustChangePassword: true },
  });
  if (!user) {
    res.status(401).json({ error: "User not found" });
    return;
  }

  if (!(await canUserAuthenticate(prisma, user.id))) {
    res.status(403).json({
      error: "Your account access has been deactivated. Contact your training provider administrator.",
      code: "ACCOUNT_DEACTIVATED",
    });
    return;
  }

  const accessToken = signAccessToken(Number(user.id), user.email);
  res.json({
    requiresTwoFactor: false,
    accessToken,
    requiresPasswordChange: user.mustChangePassword,
    user: { id: Number(user.id), name: user.name, email: user.email },
  });
});

router.post("/resend-2fa", resendLimiter, async (req, res) => {
  const parsed = resendSchema.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
    return;
  }
  let payload;
  try {
    payload = verifyPending2FAToken(parsed.data.pendingToken);
  } catch {
    res.status(401).json({ error: "Invalid or expired session. Please sign in again." });
    return;
  }

  const globallyEnabled = await getBoolSetting(prisma, EMAIL_2FA_ENABLED_KEY, false);
  if (!globallyEnabled) {
    res.status(409).json({ error: "Two-factor authentication is currently disabled by admin settings." });
    return;
  }

  const user = await prisma.user.findUnique({
    where: { id: BigInt(payload.sub) },
    select: { id: true, name: true, email: true, password: true },
  });
  if (!user) {
    res.status(401).json({ error: "User not found" });
    return;
  }

  try {
    await issueEmailChallengeAndSend(prisma, user.id, user.email, clientIp(req));
  } catch (e) {
    const detail = e instanceof Error ? e.message : "unknown smtp error";
    console.error("[auth/resend-2fa] failed to send code:", detail);
    res.status(503).json({
      error: "Could not send verification code. Check MAIL_MODE/SMTP settings or server logs.",
      ...(process.env.NODE_ENV !== "production" ? { detail } : {}),
    });
    return;
  }

  res.json({ ok: true, maskedEmail: maskEmail(user.email) });
});

router.post("/logout", requireAuth, async (_req: AuthedRequest, res) => {
  res.json({ ok: true });
});

router.get("/me", requireAuth, async (req: AuthedRequest, res) => {
  if (!(await canUserAuthenticate(prisma, req.auth!.userId))) {
    return void res.status(403).json({
      error: "Your account access has been deactivated. Contact your training provider administrator.",
      code: "ACCOUNT_DEACTIVATED",
    });
  }
  const user = await prisma.user.findUnique({
    where: { id: req.auth!.userId },
    select: { id: true, name: true, email: true, mustChangePassword: true, passwordChangedAt: true },
  });
  if (!user) return void res.status(404).json({ error: "User not found." });
  res.json({
    user: {
      id: Number(user.id),
      name: user.name,
      email: user.email,
      mustChangePassword: user.mustChangePassword,
      passwordChangedAt: user.passwordChangedAt?.toISOString() ?? null,
    },
  });
});

router.post("/change-password-required", requireAuth, async (req: AuthedRequest, res) => {
  const parsed = changePasswordRequiredSchema.safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  if (parsed.data.newPassword !== parsed.data.confirmPassword) {
    return void res.status(422).json({ error: "New password and confirmation do not match." });
  }
  const user = await prisma.user.findUnique({
    where: { id: req.auth!.userId },
    select: { id: true, mustChangePassword: true },
  });
  if (!user) return void res.status(404).json({ error: "User not found." });
  if (!user.mustChangePassword) return void res.status(409).json({ error: "Password reset is not required for this user." });

  const passwordHash = await bcrypt.hash(parsed.data.newPassword, 12);
  await prisma.user.update({
    where: { id: user.id },
    data: { password: passwordHash, mustChangePassword: false, passwordChangedAt: new Date() },
  });
  res.json({ ok: true, mustChangePassword: false });
});

router.post("/change-password", requireAuth, async (req: AuthedRequest, res) => {
  const parsed = changePasswordSchema.safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  if (parsed.data.newPassword !== parsed.data.confirmPassword) {
    return void res.status(422).json({ error: "New password and confirmation do not match." });
  }
  const user = await prisma.user.findUnique({
    where: { id: req.auth!.userId },
    select: { id: true, password: true },
  });
  if (!user) return void res.status(404).json({ error: "User not found." });
  const ok = await bcrypt.compare(parsed.data.currentPassword, user.password);
  if (!ok) return void res.status(422).json({ error: "Current password is incorrect." });

  const passwordHash = await bcrypt.hash(parsed.data.newPassword, 12);
  await prisma.user.update({
    where: { id: user.id },
    data: { password: passwordHash, mustChangePassword: false, passwordChangedAt: new Date() },
  });
  res.json({ ok: true });
});

router.post("/reset-password", async (req, res) => {
  const parsed = resetPasswordWithTokenSchema.safeParse(req.body);
  if (!parsed.success) return void res.status(400).json({ error: "Invalid request", details: parsed.error.flatten() });
  if (parsed.data.newPassword !== parsed.data.confirmPassword) {
    return void res.status(422).json({ error: "New password and confirmation do not match." });
  }

  let payload;
  try {
    payload = verifyPasswordResetToken(parsed.data.token);
  } catch {
    return void res.status(401).json({ error: "Invalid or expired reset link. Ask an administrator to resend welcome email." });
  }

  const user = await prisma.user.findUnique({
    where: { id: BigInt(payload.sub) },
    select: { id: true, email: true },
  });
  if (!user || user.email.toLowerCase() !== payload.email.toLowerCase()) {
    return void res.status(401).json({ error: "Invalid or expired reset link." });
  }

  const passwordHash = await bcrypt.hash(parsed.data.newPassword, 12);
  await prisma.user.update({
    where: { id: user.id },
    data: { password: passwordHash, mustChangePassword: false, passwordChangedAt: new Date() },
  });
  res.json({ ok: true });
});

function maskEmail(email: string): string {
  const parts = email.split("@");
  if (parts.length !== 2) return email;
  const [local, domain] = parts;
  const localMasked =
    local.length <= 2
      ? "*".repeat(Math.max(local.length, 1))
      : `${local[0]}${"*".repeat(Math.max(local.length - 2, 1))}${local[local.length - 1]}`;
  return `${localMasked}@${domain}`;
}

export default router;
