import { Admin } from '../models/Admin.js';
import { ApiError } from '../utils/ApiError.js';
import { asyncHandler } from '../utils/asyncHandler.js';

// GET /api/admins
export const listAdmins = asyncHandler(async (req, res) => {
  const admins = await Admin.findAll();
  res.json({ success: true, admins });
});

// POST /api/admins — every admin is equal in this app, so any signed-in
// admin can add another one (same as running scripts/createAdmin.js).
export const createAdmin = asyncHandler(async (req, res) => {
  const { name, email, password } = req.body;
  if (!name || !email || !password) {
    throw new ApiError(400, 'Name, email and password are required');
  }
  if (password.length < 8) throw new ApiError(400, 'Password must be at least 8 characters');

  const normalizedEmail = email.toLowerCase().trim();
  const existing = await Admin.findByEmail(normalizedEmail);
  if (existing) throw new ApiError(409, 'An admin with that email already exists');

  const admin = await Admin.create({ name: name.trim(), email: normalizedEmail, password });
  res.status(201).json({ success: true, admin });
});

// DELETE /api/admins/:id
export const removeAdmin = asyncHandler(async (req, res) => {
  const { id } = req.params;

  if (Number(id) === req.admin.id) {
    throw new ApiError(400, 'Use your profile page to manage your own account');
  }

  const count = await Admin.count();
  if (count <= 1) {
    throw new ApiError(400, 'At least one admin must remain');
  }

  const deleted = await Admin.delete(id);
  if (!deleted) throw new ApiError(404, 'Admin not found');

  res.json({ success: true });
});
