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65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const mongoose = require('mongoose');
const { asyncController } = require('../utils/asyncController');
const { recordAuditTrail } = require('../services/auditTrailService');
const AdminUser = require('../models/AdminUser');
const { ensureAdminInitialized } = require('../services/adminAuthService');
const { isValidPersonName } = require('../validation/commonValidation');
const { env } = require('../configs/env');

const JWT_SECRET = env.jwtSecret;
const BCRYPT_SALT_ROUNDS = 12;

const USERNAME_PATTERN = /^[a-z0-9._-]{3,30}$/;

const buildAuthUser = (admin) => ({
  id: String(admin._id),
  username: admin.username,
  name: admin.name,
  role: 'admin',
  isActive: admin.isActive !== false,
});

const generateToken = (user, sessionToken) => {
  if (!JWT_SECRET) {
    throw new Error('JWT_SECRET is not configured');
  }

  const payload = { id: user.id };
  if (sessionToken) payload.st = sessionToken;

  return jwt.sign(payload, JWT_SECRET, {
    expiresIn: env.jwtExpire,
  });
};

const normalizeUsername = (value) => String(value || '').trim().toLowerCase();

const buildManagedUser = (admin) => ({
  id: String(admin._id),
  username: admin.username,
  name: admin.name,
  role: admin.role || 'admin',
  isActive: admin.isActive !== false,
  createdAt: admin.createdAt,
  updatedAt: admin.updatedAt,
});

const login = asyncController(async (req, res) => {
  await ensureAdminInitialized();

  const identifier = String(req.body?.email || req.body?.username || '').trim();
  const password = String(req.body?.password || '');

  if (!identifier || !password) {
    return res.status(400).json({ message: 'Username and password are required' });
  }

  const admin = await AdminUser.findOne({
    username: identifier.toLowerCase(),
  }).select('+passwordHash');

  if (!admin) {
    return res.status(401).json({ message: 'Incorrect username or password.' });
  }

  if (admin.isActive === false) {
    return res.status(403).json({ message: 'This account is inactive' });
  }

  const isValidPass = await bcrypt.compare(password, admin.passwordHash || '');
  if (!isValidPass) {
    return res.status(401).json({ message: 'Incorrect username or password.' });
  }

  const sessionToken = crypto.randomBytes(32).toString('hex');
  await AdminUser.findByIdAndUpdate(admin._id, { sessionToken });

  const user = buildAuthUser(admin);
  const token = generateToken(user, sessionToken);

  void recordAuditTrail({
    req,
    actor: { id: user.id, name: user.name },
    action: 'login',
    moduleName: 'auth',
    summary: 'Admin logged in',
    endpoint: 'POST /api/auth/login',
    method: 'POST',
    statusCode: 200,
  });

  res.cookie('token', token, {
    httpOnly: true,
    secure: env.isProduction,
    sameSite: 'strict',
  });

  return res.json({ token, user });
});

const register = async (req, res) => {
  return res.status(501).json({ message: 'Registration is disabled for this project' });
};

const getMe = (req, res) => {
  return res.json(req.user || null);
};

const updateProfile = asyncController(async (req, res) => {
  await ensureAdminInitialized();

  const { currentPassword, newName, newUsername, newPassword } = req.body || {};

  if (!currentPassword) {
    return res.status(400).json({ message: 'Current password is required' });
  }

  const adminId = req.user?.id || req.user?._id;
  if (!adminId) {
    return res.status(401).json({ message: 'Not authorized, invalid token' });
  }

  const admin = await AdminUser.findById(adminId).select('+passwordHash');
  if (!admin) {
    return res.status(404).json({ message: 'Account not found' });
  }

  const isCurrentPasswordValid = await bcrypt.compare(currentPassword, admin.passwordHash || '');
  if (!isCurrentPasswordValid) {
    return res.status(401).json({ message: 'Current password is incorrect' });
  }

  if (newUsername !== undefined) {
    const normalizedUsername = normalizeUsername(newUsername);

    if (!USERNAME_PATTERN.test(normalizedUsername)) {
      return res.status(400).json({
        message: 'Username must be 3-30 characters using letters, numbers, dots, dashes, or underscores',
      });
    }

    if (normalizedUsername !== admin.username) {
      const usernameInUse = await AdminUser.findOne({
        username: normalizedUsername,
        _id: { $ne: admin._id },
      })
        .select('_id')
        .lean();

      if (usernameInUse) {
        return res.status(409).json({ message: 'Username is already taken' });
      }

      admin.username = normalizedUsername;
    }
  }

  if (newName && newName.trim()) {
    if (!isValidPersonName(newName)) {
      return res.status(400).json({ message: 'Display name must contain letters only (no numbers)' });
    }
    admin.name = newName.trim();
  }

  if (newPassword) {
    if (newPassword.length < env.adminPasswordMinLength) {
      return res.status(400).json({ message: `New password must be at least ${env.adminPasswordMinLength} characters` });
    }

    admin.passwordHash = await bcrypt.hash(newPassword, BCRYPT_SALT_ROUNDS);
  }

  await admin.save();

  const updatedAdmin = await AdminUser.findById(admin._id).select('+sessionToken').lean();
  const user = buildAuthUser(admin);
  const token = generateToken(user, updatedAdmin?.sessionToken || undefined);

  res.cookie('token', token, {
    httpOnly: true,
    secure: env.isProduction,
    sameSite: 'strict',
  });

  return res.json({ user, message: 'Profile updated successfully' });
});

const listUsers = asyncController(async (_req, res) => {
  await ensureAdminInitialized();
  const users = await AdminUser.find({})
    .sort({ createdAt: 1 })
    .select('_id username name role isActive createdAt updatedAt')
    .lean();

  return res.json((users || []).map(buildManagedUser));
});

const createUser = asyncController(async (req, res) => {
  await ensureAdminInitialized();

  const username = normalizeUsername(req.body?.username);
  const name = String(req.body?.name || '').trim();
  const password = String(req.body?.password || '');
  const isActive = req.body?.isActive !== false;

  if (!USERNAME_PATTERN.test(username)) {
    return res.status(400).json({
      message: 'Username must be 3-30 characters using letters, numbers, dots, dashes, or underscores',
    });
  }

  if (!name) {
    return res.status(400).json({ message: 'Display name is required' });
  }

  if (!isValidPersonName(name)) {
    return res.status(400).json({ message: 'Display name must contain letters only (no numbers)' });
  }

  if (password.length < env.adminPasswordMinLength) {
    return res.status(400).json({ message: `Password must be at least ${env.adminPasswordMinLength} characters` });
  }

  const usernameInUse = await AdminUser.findOne({ username }).select('_id').lean();
  if (usernameInUse) {
    return res.status(409).json({ message: 'Username is already taken' });
  }

  const passwordHash = await bcrypt.hash(password, BCRYPT_SALT_ROUNDS);
  const admin = await AdminUser.create({
    username,
    name,
    passwordHash,
    role: 'admin',
    isActive,
  });

  return res.status(201).json(buildManagedUser(admin));
});

const updateUser = asyncController(async (req, res) => {
  await ensureAdminInitialized();

  const targetId = String(req.params?.id || '').trim();
  if (!targetId) {
    return res.status(400).json({ message: 'User id is required' });
  }

  const admin = await AdminUser.findById(targetId).select('+passwordHash');
  if (!admin) {
    return res.status(404).json({ message: 'User not found' });
  }

  const requesterId = String(req.user?.id || req.user?._id || '');

  const hasUsername = Object.prototype.hasOwnProperty.call(req.body || {}, 'username');
  const hasName = Object.prototype.hasOwnProperty.call(req.body || {}, 'name');
  const hasPassword = Object.prototype.hasOwnProperty.call(req.body || {}, 'password');
  const hasIsActive = Object.prototype.hasOwnProperty.call(req.body || {}, 'isActive');

  if (hasUsername) {
    const username = normalizeUsername(req.body?.username);
    if (!USERNAME_PATTERN.test(username)) {
      return res.status(400).json({
        message: 'Username must be 3-30 characters using letters, numbers, dots, dashes, or underscores',
      });
    }

    if (username !== admin.username) {
      const usernameInUse = await AdminUser.findOne({ username, _id: { $ne: admin._id } }).select('_id').lean();
      if (usernameInUse) {
        return res.status(409).json({ message: 'Username is already taken' });
      }
      admin.username = username;
    }
  }

  if (hasName) {
    const name = String(req.body?.name || '').trim();
    if (!name) {
      return res.status(400).json({ message: 'Display name is required' });
    }
    if (!isValidPersonName(name)) {
      return res.status(400).json({ message: 'Display name must contain letters only (no numbers)' });
    }
    admin.name = name;
  }

  if (hasPassword) {
    const password = String(req.body?.password || '');
    if (password && password.length < env.adminPasswordMinLength) {
      return res.status(400).json({ message: `Password must be at least ${env.adminPasswordMinLength} characters` });
    }
    if (password) {
      admin.passwordHash = await bcrypt.hash(password, BCRYPT_SALT_ROUNDS);
    }
  }

  if (hasIsActive) {
    const nextIsActive = req.body?.isActive !== false;

    if (requesterId && requesterId === String(admin._id) && !nextIsActive) {
      return res.status(400).json({ message: 'You cannot deactivate your own account' });
    }

    if (!nextIsActive && admin.isActive !== false) {
      const session = await mongoose.startSession();
      let saved;
      try {
        await session.withTransaction(async () => {
          const activeCount = await AdminUser.countDocuments(
            { isActive: { $ne: false } },
            { session }
          );
          if (activeCount <= 1) {
            throw Object.assign(new Error('At least one active admin account is required'), { statusCode: 400 });
          }
          admin.isActive = false;
          saved = await admin.save({ session });
        });
      } catch (txErr) {
        if (txErr.statusCode === 400) {
          return res.status(400).json({ message: txErr.message });
        }
        throw txErr;
      } finally {
        await session.endSession();
      }
      return res.json(buildManagedUser(saved || admin));
    }

    admin.isActive = nextIsActive;
  }

  await admin.save();
  return res.json(buildManagedUser(admin));
});

const deleteUser = asyncController(async (req, res) => {
  await ensureAdminInitialized();

  const targetId = String(req.params?.id || '').trim();
  if (!targetId) {
    return res.status(400).json({ message: 'User id is required' });
  }

  const requesterId = String(req.user?.id || req.user?._id || '');
  if (requesterId && requesterId === targetId) {
    return res.status(400).json({ message: 'You cannot delete your own account' });
  }

  const targetUser = await AdminUser.findById(targetId).select('_id isActive').lean();
  if (!targetUser) {
    return res.status(404).json({ message: 'User not found' });
  }

  if (targetUser.isActive !== false) {
    const session = await mongoose.startSession();
    try {
      await session.withTransaction(async () => {
        const activeCount = await AdminUser.countDocuments(
          { isActive: { $ne: false } },
          { session }
        );
        if (activeCount <= 1) {
          throw Object.assign(new Error('At least one active admin account is required'), { statusCode: 400 });
        }
        const deleted = await AdminUser.findByIdAndDelete(targetId, { session }).select('_id').lean();
        if (!deleted) {
          throw Object.assign(new Error('User not found'), { statusCode: 404 });
        }
      });
    } catch (txErr) {
      if (txErr.statusCode === 400) return res.status(400).json({ message: txErr.message });
      if (txErr.statusCode === 404) return res.status(404).json({ message: txErr.message });
      throw txErr;
    } finally {
      await session.endSession();
    }
    return res.status(204).send();
  }

  const deleted = await AdminUser.findByIdAndDelete(targetId).select('_id').lean();
  if (!deleted) {
    return res.status(404).json({ message: 'User not found' });
  }

  return res.status(204).send();
});

const logout = asyncController(async (req, res) => {
  const token = req.cookies?.token;
  let actorId = 'unknown';
  let actorName = 'Administrator';
  if (token) {
    try {
      const decoded = jwt.decode(token);
      if (decoded?.id) {
        actorId = String(decoded.id);
        const admin = await AdminUser.findById(actorId).select('name').lean();
        if (admin?.name) actorName = admin.name;
      }
    } catch (_) {}
  }

  if (actorId !== 'unknown') {
    try {
      await AdminUser.findByIdAndUpdate(actorId, { sessionToken: null });
    } catch (_) {}
  }

  void recordAuditTrail({
    req,
    actor: { id: actorId, name: actorName },
    action: 'logout',
    moduleName: 'auth',
    summary: 'Admin logged out',
    endpoint: 'POST /api/auth/logout',
    method: 'POST',
    statusCode: 200,
  });

  res.clearCookie('token', { httpOnly: true, secure: env.isProduction, sameSite: 'strict' });
  return res.json({ message: 'Logged out' });
});

module.exports = {
  login,
  logout,
  register,
  getMe,
  updateProfile,
  listUsers,
  createUser,
  updateUser,
  deleteUser,
};