import bcrypt from "bcryptjs";
import crypto from "crypto";
import { Types } from "mongoose";
import cloudinary from "../config/cloudinary";
import Admin from "../models/admin";
import User from "../models/users";
import Quiz from "../models/quiz";
import Question from "../models/question";
import QuizResult from "../models/quizResult";
import QuizAttempt from "../models/quizAttempt";
import Attendance from "../models/attendance";
import PsychometricTest from "../models/psychometricTest";
import PsychometricResult from "../models/psychometricResult";
import ZiplineAttempt from "../models/ziplineAttempt";
import RewardRedemption from "../models/rewardRedemption";
import DesktopSession from "../models/desktopSession";
import { toKolkataTime, fromKolkataTime } from "../utils/timezone";
import { expireQuizzes } from "../cron/quizExpiry";
import { sendEmployeeWelcomeEmail } from "../utils/emailService";
import { getLatestActiveDesktopRelease } from "./desktopReleaseService";
import speakeasy from "speakeasy";
import QRCode from "qrcode";

const ALLOWED_DOMAIN = "@eglogics.com";

const notFound = (msg: string): Error & { statusCode: number } =>
  Object.assign(new Error(msg), { statusCode: 404 });

const badRequest = (msg: string): Error & { statusCode: number } =>
  Object.assign(new Error(msg), { statusCode: 400 });

const ADMIN_USER_EDITABLE_FIELDS = [
  "name",
  "email",
  "phone",
  "address",
  "department",
  "designation",
  "employee_id",
  "joining_date",
  "status",
  "total_points",
] as const;

// ─── Self ─────────────────────────────────────────────────────────────────────

export const getAdminById = async (id: string) => Admin.findById(id);

export const getAllAdmins = async (page = 1, limit = 10) => {
  const skip = (page - 1) * limit;
  const [admins, total] = await Promise.all([
    Admin.find()
      .select("_id name email role avatar createdAt updatedAt")
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit)
      .lean(),
    Admin.countDocuments(),
  ]);

  return {
    admins,
    pagination: {
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
      hasNextPage: page < Math.ceil(total / limit),
      hasPrevPage: page > 1,
    },
  };
};

export const deleteAdmin = async (
  id: string,
  currentAdminId: string,
): Promise<void> => {
  if (!Types.ObjectId.isValid(id)) {
    throw badRequest("Invalid admin id");
  }

  if (id === currentAdminId) {
    throw badRequest("You cannot delete your own admin account");
  }

  const admin = await Admin.findByIdAndDelete(id);
  if (!admin) throw notFound("Admin not found");
};

export const updateAdmin = async (
  id: string,
  { name, email }: { name?: string; email?: string },
) =>
  Admin.findByIdAndUpdate(
    id,
    { name, email },
    { new: true, runValidators: true },
  );

export const uploadAdminAvatar = async (
  id: string,
  fileBuffer: Buffer,
  mimetype: string,
) => {
  const base64 = fileBuffer.toString("base64");
  const dataUri = `data:${mimetype};base64,${base64}`;
  const result = await cloudinary.uploader.upload(dataUri, {
    folder: "avatars/admins",
    transformation: [
      { width: 200, height: 200, crop: "fill", gravity: "face" },
    ],
  });
  return Admin.findByIdAndUpdate(
    id,
    { avatar: result.secure_url },
    { new: true },
  );
};

export const uploadUserAvatar = async (
  id: string,
  fileBuffer: Buffer,
  mimetype: string,
) => {
  const base64 = fileBuffer.toString("base64");
  const dataUri = `data:${mimetype};base64,${base64}`;
  const result = await cloudinary.uploader.upload(dataUri, {
    folder: "avatars/users",
    transformation: [
      { width: 200, height: 200, crop: "fill", gravity: "face" },
    ],
  });
  const user = await User.findByIdAndUpdate(
    id,
    { avatar: result.secure_url },
    { new: true },
  );
  if (!user) throw notFound("User not found");
  return user;
};

export const changeAdminPassword = async (
  id: string,
  currentPassword: string,
  newPassword: string,
): Promise<void> => {
  const admin = await Admin.findById(id).select("+password");
  if (!admin) throw notFound("Admin not found");
  const isMatch = await bcrypt.compare(currentPassword, admin.password!);
  if (!isMatch)
    throw Object.assign(new Error("Current password is incorrect"), {
      statusCode: 401,
    });
  admin.password = await bcrypt.hash(newPassword, 10);
  await admin.save();
};

// ─── User Management ──────────────────────────────────────────────────────────

export const getAllUsers = async (
  page = 1,
  limit = 10,
  search = "",
) => {
  const skip = (page - 1) * limit;

  const filter: any = {};

  if (search.trim()) {
    filter.$or = [
      { name: { $regex: search, $options: "i" } },
      { email: { $regex: search, $options: "i" } },
      { department: { $regex: search, $options: "i" } },
      { employee_id: { $regex: search, $options: "i" } },
    ];
  }

  const [users, total] = await Promise.all([
    User.find(filter)
      .select("+password")
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit),

    User.countDocuments(filter),
  ]);

  const today = toKolkataTime(new Date(), "yyyy-MM-dd");
  const todayStart = fromKolkataTime(`${today} 00:00:00`);
  const todayEnd = new Date(todayStart.getTime() + 24 * 60 * 60 * 1000);

  const presentUserIds = await DesktopSession.distinct("user", {
    log_type: "CHECKIN",
    timestamp: { $gte: todayStart, $lt: todayEnd },
  });
  const presentSet = new Set(presentUserIds.map((id) => id.toString()));

  const usersWithAttendance = users.map((user) => {
    const { password, ...rest } = user.toObject();
    return {
      ...rest,
      has_password: Boolean(password),
      attendance: presentSet.has(user._id.toString()) ? "Present" : "Absent",
    };
  });

  return {
    users: usersWithAttendance,
    pagination: {
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
      hasNextPage: page < Math.ceil(total / limit),
      hasPrevPage: page > 1,
    },
  };
};

export const getAllUsersMinimal = async () => {
  const users = await User.find()
    .select("name email department employee_id avatar status password")
    .sort({ name: 1 })
    .lean();

  return users.map(({ password, ...rest }) => ({
    ...rest,
    has_password: Boolean(password),
  }));
};

export const getUserById = async (id: string) => {
  const user = await User.findById(id).select("+password");
  if (!user) throw notFound("User not found");
  const { password, ...rest } = user.toObject();
  return { ...rest, has_password: Boolean(password) };
};

const SET_PASSWORD_TOKEN_TTL_MS = 3 * 24 * 60 * 60 * 1000; // 3 days

const getDesktopDownloadUrl = async (): Promise<string | null> => {
  const apiBase = process.env.API_URL?.replace(/\/+$/, "");
  if (!apiBase) return null;
  try {
    const release = await getLatestActiveDesktopRelease();
    return `${apiBase}/downloads/${encodeURIComponent(release.installer_filename)}`;
  } catch {
    return null; // No active release published yet — skip the download button
  }
};

const issueEmployeeInvite = async (user: InstanceType<typeof User>): Promise<void> => {
  const rawToken = crypto.randomBytes(32).toString("hex");
  user.resetToken = crypto.createHash("sha256").update(rawToken).digest("hex");
  user.resetTokenExpiry = new Date(Date.now() + SET_PASSWORD_TOKEN_TTL_MS);
  await user.save();

  const setPasswordLink = `${process.env.ADMIN_URL}/set-password?token=${rawToken}`;
  const downloadUrl = await getDesktopDownloadUrl();

  try {
    await sendEmployeeWelcomeEmail(user.email, user.name, setPasswordLink, downloadUrl);
  } catch (error) {
    console.error("Failed to send employee welcome email:", error);
  }
};

export const createUser = async (
  name: string,
  email: string,
  profile: Record<string, unknown> = {},
) => {
  if (!email.endsWith(ALLOWED_DOMAIN))
    throw badRequest("Only @eglogics.com email addresses are allowed");
  const existing = await User.findOne({ email });
  if (existing) throw badRequest("User already exists");

  const fields: Record<string, unknown> = {};
  ADMIN_USER_EDITABLE_FIELDS.forEach((f) => {
    if (f !== "name" && f !== "email" && f !== "total_points" && profile[f] !== undefined) {
      fields[f] = profile[f];
    }
  });

  const user = await User.create({ name, email, ...fields });
  await issueEmployeeInvite(user);

  const { password, resetToken, resetTokenExpiry, refreshToken, ...rest } = user.toObject();
  return { ...rest, has_password: Boolean(password) };
};

export const resendEmployeeInvite = async (id: string): Promise<void> => {
  if (!Types.ObjectId.isValid(id)) throw badRequest("Invalid user id");

  const user = await User.findById(id).select("+password");
  if (!user) throw notFound("User not found");
  if (user.password)
    throw badRequest("This employee has already set their password");

  await issueEmployeeInvite(user);
};

export const updateUser = async (id: string, body: Record<string, unknown>) => {
  const update: Record<string, unknown> = {};
  ADMIN_USER_EDITABLE_FIELDS.forEach((f) => {
    if (body[f] !== undefined) update[f] = body[f];
  });
  const user = await User.findByIdAndUpdate(id, update, {
    new: true,
    runValidators: true,
  });
  if (!user) throw notFound("User not found");
  return user;
};

export const changeUserPassword = async (
  id: string,
  newPassword: string,
): Promise<void> => {
  const user = await User.findById(id);
  if (!user) throw notFound("User not found");
  user.password = await bcrypt.hash(newPassword, 10);
  await user.save();
};

export const deleteUser = async (id: string): Promise<void> => {
  const user = await User.findByIdAndDelete(id);
  if (!user) throw notFound("User not found");
};

// ─── Dashboard ───────────────────────────────────────────────────────────────

const roundToTwo = (value: number): number => Math.round(value * 100) / 100;

type RecentActivityItem = {
  type: string;
  title: string;
  message: string;
  createdAt: Date;
  meta?: Record<string, unknown>;
};

export const getEmployeeDetails = async (employeeId: string) => {
  if (!Types.ObjectId.isValid(employeeId)) {
    throw badRequest("Invalid employeeId");
  }

  const userObjectId = new Types.ObjectId(employeeId);

  const user = await User.findById(userObjectId)
    .select(
      "_id name email phone department designation avatar status createdAt currentStreak longestStreak lastCheckInDate quiz_points redeemed_points ",
    )
    .lean();

  if (!user) throw notFound("Employee not found");

  const [
    attendanceStats,
    quizAttemptCount,
    quizResultStats,
    ziplineStats,
    rewardStats,
    latestRewards,
    attendanceForTimeline,
    quizAttemptsForTimeline,
    quizResultsForTimeline,
    ziplineAttemptsForTimeline,
    rewardsForTimeline,
  ] = await Promise.all([
    Attendance.aggregate([
      { $match: { user: userObjectId } },
      { $unwind: "$sessions" },
      { $group: { _id: null, totalCheckIns: { $sum: 1 } } },
    ]),
    QuizAttempt.countDocuments({ user: userObjectId }),
    QuizResult.aggregate([
      { $match: { user: userObjectId } },
      {
        $group: {
          _id: null,
          completedQuizzes: { $sum: 1 },
          averageQuizScore: { $avg: "$score" },
          highestQuizScore: { $max: "$score" },
          totalQuizPoints: { $sum: "$score" },
        },
      },
    ]),
    ZiplineAttempt.aggregate([
      { $match: { user: userObjectId } },
      {
        $group: {
          _id: null,
          totalGamesPlayed: { $sum: 1 },
          totalGamesCompleted: {
            $sum: {
              $cond: [
                {
                  $or: [
                    { $eq: ["$status", "COMPLETED"] },
                    { $ne: [{ $ifNull: ["$completedAt", null] }, null] },
                  ],
                },
                1,
                0,
              ],
            },
          },
          averageGameScore: { $avg: { $ifNull: ["$score", 0] } },
          highestGameScore: { $max: { $ifNull: ["$score", 0] } },
          fastestCompletionTime: {
            $min: {
              $cond: [
                {
                  $and: [
                    { $ne: [{ $ifNull: ["$completedAt", null] }, null] },
                    { $gt: [{ $ifNull: ["$timeTaken", 0] }, 0] },
                  ],
                },
                "$timeTaken",
                null,
              ],
            },
          },
        },
      },
    ]),
    RewardRedemption.aggregate([
      {
        $match: {
          user: userObjectId,
          status: { $in: ["approved", "fulfilled"] },
        },
      },
      { $group: { _id: null, totalRewardsRedeemed: { $sum: 1 } } },
    ]),
    RewardRedemption.find({ user: userObjectId })
      .select("_id reward status requestedAt processedAt")
      .populate("reward", "name description type points_required image_url")
      .sort({ requestedAt: -1 })
      .limit(5)
      .lean(),
    Attendance.find({ user: userObjectId })
      .select("date sessions createdAt")
      .sort({ date: -1 })
      .limit(10)
      .lean(),
    QuizAttempt.find({ user: userObjectId })
      .select("_id quiz startedAt createdAt status")
      .populate("quiz", "title")
      .sort({ startedAt: -1 })
      .limit(10)
      .lean(),
    QuizResult.find({ user: userObjectId })
      .select("_id quiz score total_points submitted_at")
      .populate("quiz", "title")
      .sort({ submitted_at: -1 })
      .limit(10)
      .lean(),
    ZiplineAttempt.find({ user: userObjectId })
      .select(
        "_id puzzle score timeTaken startedAt completedAt attemptedAt status",
      )
      .populate("puzzle", "title difficulty")
      .sort({ attemptedAt: -1 })
      .limit(10)
      .lean(),
    RewardRedemption.find({ user: userObjectId })
      .select("_id reward status requestedAt")
      .populate("reward", "name points_required")
      .sort({ requestedAt: -1 })
      .limit(10)
      .lean(),
  ]);

  const quizStatsRow = quizResultStats[0] || {};
  const gameStatsRow = ziplineStats[0] || {};
  const totalPointsEarned = user.quiz_points || 0;
  const totalPointsRedeemed = user.redeemed_points || 0;

  const recentActivity: RecentActivityItem[] = [
    ...attendanceForTimeline.flatMap((record: any) =>
      (record.sessions || []).map((session: any) => ({
        type: "attendance_check_in",
        title: "Attendance Check-In",
        message: "Employee checked in",
        createdAt: new Date(session.check_in),
        meta: { attendanceId: record._id, date: record.date },
      })),
    ),
    ...quizAttemptsForTimeline.map((attempt: any) => ({
      type: "quiz_started",
      title: "Quiz Started",
      message: `Started ${attempt.quiz?.title || "a quiz"}`,
      createdAt: new Date(attempt.startedAt || attempt.createdAt),
      meta: { attemptId: attempt._id, quizId: attempt.quiz?._id },
    })),
    ...quizResultsForTimeline.map((result: any) => ({
      type: "quiz_completed",
      title: "Quiz Completed",
      message: `Completed ${result.quiz?.title || "a quiz"}`,
      createdAt: new Date(result.submitted_at),
      meta: {
        resultId: result._id,
        quizId: result.quiz?._id,
        score: result.score,
        totalPoints: result.total_points,
      },
    })),
    ...ziplineAttemptsForTimeline.map((attempt: any) => ({
      type: attempt.completedAt ? "zipline_completed" : "zipline_started",
      title: attempt.completedAt ? "Zipline Completed" : "Zipline Started",
      message: `${attempt.completedAt ? "Completed" : "Started"} ${attempt.puzzle?.title || "Zipline"}`,
      createdAt: new Date(
        attempt.completedAt || attempt.startedAt || attempt.attemptedAt,
      ),
      meta: {
        attemptId: attempt._id,
        puzzleId: attempt.puzzle?._id,
        score: attempt.score || 0,
        timeTaken: attempt.timeTaken || 0,
      },
    })),
    ...rewardsForTimeline.map((redemption: any) => ({
      type: "reward_redeemed",
      title: "Reward Redeemed",
      message: `Requested ${redemption.reward?.name || "a reward"}`,
      createdAt: new Date(redemption.requestedAt),
      meta: {
        redemptionId: redemption._id,
        rewardId: redemption.reward?._id,
        status: redemption.status,
      },
    })),
  ]
    .filter((item) => !Number.isNaN(item.createdAt.getTime()))
    .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
    .slice(0, 10);

  return {
    employee: {
      _id: user._id,
      name: user.name,
      email: user.email,
      phone: user.phone || null,
      department: user.department || null,
      designation: user.designation || null,
      profileImage: user.avatar || null,
      is_active: user.status === "active",
      createdAt: user.createdAt,
    },
    attendance: {
      currentStreak: user.currentStreak || 0,
      longestStreak: user.longestStreak || 0,
      totalCheckIns: attendanceStats[0]?.totalCheckIns || 0,
      lastCheckInDate: user.lastCheckInDate || null,
    },
    quizStats: {
      totalQuizAttempts: quizAttemptCount,
      completedQuizzes: quizStatsRow.completedQuizzes || 0,
      averageQuizScore: roundToTwo(quizStatsRow.averageQuizScore || 0),
      highestQuizScore: quizStatsRow.highestQuizScore || 0,
      totalQuizPoints: quizStatsRow.totalQuizPoints || 0,
    },
    gameStats: {
      totalGamesPlayed: gameStatsRow.totalGamesPlayed || 0,
      totalGamesCompleted: gameStatsRow.totalGamesCompleted || 0,
      averageGameScore: roundToTwo(gameStatsRow.averageGameScore || 0),
      highestGameScore: gameStatsRow.highestGameScore || 0,
      fastestCompletionTime: gameStatsRow.fastestCompletionTime || null,
    },
    points: {
      totalPointsEarned,
      totalPointsRedeemed,
      availablePoints: totalPointsEarned - totalPointsRedeemed,
    },
    rewards: {
      totalRewardsRedeemed: rewardStats[0]?.totalRewardsRedeemed || 0,
      latestRewards,
    },
    recentActivity,
  };
};

export const getDashboard = async () => {
  const now = new Date();
  const today = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);

  await expireQuizzes();

  const [
    totalEmployees,
    newThisMonth,
    recentEmployees,
    totalQuestions,
    totalQuestionPoints,
    quizActive,
    quizDraft,
    quizInactive,
    todayAttendance,
    topPerformers,
    psychometricTests,
    psychometricCompleted,
    recentQuizResults,
  ] = await Promise.all([
    User.countDocuments(),
    User.countDocuments({ createdAt: { $gte: startOfMonth } }),
    User.find()
      .select("name email avatar joining_date createdAt")
      .sort({ createdAt: -1 })
      .limit(6)
      .lean(),
    Question.countDocuments(),
    Question.aggregate([
      { $group: { _id: null, total: { $sum: "$points" } } },
    ]).then((r) => r[0]?.total || 0),
    Quiz.countDocuments({ status: "active" }),
    Quiz.countDocuments({ status: "draft" }),
    Quiz.countDocuments({ status: "inactive" }),
    Attendance.find({ date: today })
      .populate("user", "name email avatar")
      .select("user sessions total_minutes")
      .lean(),
    User.find({
      $expr: {
        $gt: [
          { $subtract: ["$quiz_points", { $ifNull: ["$redeemed_points", 0] }] },
          0,
        ],
      },
    })
      .select("name avatar quiz_points redeemed_points earned_points spin_wheel_points")
      .lean(),
    PsychometricTest.countDocuments(),
    PsychometricResult.countDocuments(),
    QuizResult.find()
      .populate("user", "name email")
      .populate("quiz", "title")
      .select("user quiz score total_points submitted_at")
      .sort({ submitted_at: -1 })
      .limit(5)
      .lean(),
  ]);

  const totalQuizzes = quizActive + quizDraft + quizInactive;

  // Today's attendance stats
  const presentToday = todayAttendance.length;
  const checkedInNow = todayAttendance.filter((a) =>
    a.sessions.some((s) => s.check_out === null),
  ).length;
  const avgMinutes =
    presentToday > 0
      ? Math.round(
          todayAttendance.reduce((sum, a) => sum + a.total_minutes, 0) /
            presentToday,
        )
      : 0;

  // Initials helper
  const getInitials = (name: string) => {
    const parts = name.trim().split(/\s+/);
    return parts.length >= 2
      ? (parts[0][0] + parts[parts.length - 1][0]).toUpperCase()
      : parts[0].substring(0, 2).toUpperCase();
  };

  return {
    stats: {
      total_employees: totalEmployees,
      new_this_month: newThisMonth,
      active_quizzes: quizActive,
      question_bank: totalQuestions,
      total_question_points: totalQuestionPoints,
    },
    quiz_overview: {
      total: totalQuizzes,
      active: quizActive,
      draft: quizDraft,
      inactive: quizInactive,
    },
    attendance_today: {
      present: presentToday,
      checked_in_now: checkedInNow,
      absent: totalEmployees - presentToday,
      avg_minutes: avgMinutes,
    },
    top_performers: topPerformers
      .map((u) => ({
        name: u.name,
        avatar: u.avatar,
        initials: getInitials(u.name),
        earned_points: u.earned_points || 0,
        redeemed_points: u.redeemed_points || 0,
        total_points: (u.earned_points || 0) - (u.redeemed_points || 0),
      }))
      .sort((a, b) => b.total_points - a.total_points)
      .map((u, i) => ({ ...u, rank: i + 1 })),
    recent_employees: recentEmployees.map((u) => ({
      _id: u._id,
      name: u.name,
      email: u.email,
      avatar: u.avatar,
      initials: getInitials(u.name),
      joining_date: u.joining_date,
    })),
    recent_quiz_results: recentQuizResults
      .filter((r) => r.quiz !== null && r.user !== null)
      .map((r) => {
        const user = r.user as unknown as { name: string; email: string };
        const quiz = r.quiz as unknown as { title: string };
        return {
          user_name: user.name,
          user_email: user.email,
          quiz_title: quiz.title,
          score: r.score,
          total_points: r.total_points,
          submitted_at: r.submitted_at,
        };
      }),
    psychometric_overview: {
      total_tests: psychometricTests,
      total_completed: psychometricCompleted,
    },
  };
};

export const getLeaderboard = async () => {
  return User.find({ total_points: { $gt: 0 } })
    .select("name email department designation total_points")
    .sort({ total_points: -1 })
    .lean();
};

//───────────────────── 2FA ─────────────────────────────────────────────────────────

export const generate2FASetup = async (adminId: string) => {
  const admin = await Admin.findById(adminId);

  if (!admin) {
    throw new Error("Admin not found");
  }

  const secret = speakeasy.generateSecret({
    name: `Employee Engagement (${admin.email})`,
    issuer: "Employee Engagement",
    length: 20,
  });

  admin.twoFactorSecret = secret.base32;
  await admin.save();

  const qrCode = await QRCode.toDataURL(secret.otpauth_url!);

  return {
    qrCode,
    manualKey: secret.base32,
  };
};

export const verifyAndEnable2FA = async (adminId: string, code: string) => {
  const admin = await Admin.findById(adminId);

  if (!admin) {
    throw new Error("Admin not found");
  }

  if (!admin.twoFactorSecret) {
    throw new Error("2FA setup not initiated");
  }

  const verified = speakeasy.totp.verify({
    secret: admin.twoFactorSecret,
    encoding: "base32",
    token: code,
    window: 1,
  });

  if (!verified) {
    throw new Error("Invalid verification code");
  }

  admin.twoFactorEnabled = true;
  admin.twoFactorVerifiedAt = new Date();

  await admin.save();

  return {
    enabled: true,
  };
};

export const disable2FA = async ({
  adminId,
  code,
}: {
  adminId: string;
  code: string;
}) => {
  const admin = await Admin.findById(adminId).select("+password");

  if (!admin) {
    throw new Error("Admin not found");
  }

  if (!admin.password) {
    throw new Error("Password not found");
  }

  // const passwordValid = await bcrypt.compare(password, admin.password);

  // if (!passwordValid) {
  //   throw new Error("Invalid password");
  // }

  if (!admin.twoFactorSecret) {
    throw new Error("2FA secret not found");
  }

  const verified = speakeasy.totp.verify({
    secret: admin.twoFactorSecret,
    encoding: "base32",
    token: code,
    window: 1,
  });

  if (!verified) {
    throw new Error("Invalid verification code");
  }

  admin.twoFactorEnabled = false;
  admin.twoFactorSecret = undefined;
  admin.twoFactorVerifiedAt = undefined;

  await admin.save();

  return {
    enabled: false,
  };
};

export const get2FAStatus = async (adminId: string) => {
  const admin = await Admin.findById(adminId);

  if (!admin) {
    throw new Error("Admin not found");
  }

  return {
    enabled: Boolean(admin.twoFactorEnabled),
    verifiedAt: admin.twoFactorVerifiedAt || null,
  };
};
