import { findByEmail, findById } from '../repositories/adminRepository.js';
import generateToken from '../utils/generateToken.js';

const login = async (email, password) => {
  const admin = await findByEmail(email);
  if (!admin) {
    throw Object.assign(new Error('Invalid email or password'), { statusCode: 401 });
  }

  const isMatch = await admin.comparePassword(password);
  if (!isMatch) {
    throw Object.assign(new Error('Invalid email or password'), { statusCode: 401 });
  }

  if (admin.status === 'INACTIVE') {
    throw Object.assign(
      new Error('This account has been deactivated. Contact an administrator.'),
      { statusCode: 403 }
    );
  }

  // Track last login for staff management (never blocks the login itself)
  try {
    admin.lastLoginAt = new Date();
    await admin.save();
  } catch {
    // non-fatal
  }

  const token = generateToken(admin._id);
  const adminObj = admin.toJSON();
  delete adminObj.password;

  return { token, admin: adminObj };
};

const getMe = async (adminId) => {
  const admin = await findById(adminId);
  if (!admin) {
    throw Object.assign(new Error('Admin not found'), { statusCode: 404 });
  }
  return admin;
};

export default { login, getMe };
