const asyncHandler = require('../middlewares/asyncHandler');
const {
  getExternalAuditors,
  getExternalAuditorById,
  createExternalAuditor
} = require('../repositories/externalAuditorsRepository');

// List external auditors (optional ?q= for hot search)
exports.getExternalAuditors = asyncHandler(async (req, res) => {
  const q = req.query.q || '';
  const rows = await getExternalAuditors(q);
  res.status(200).json({ success: true, data: rows });
});

// Get one external auditor by id
exports.getExternalAuditorById = asyncHandler(async (req, res) => {
  const { id } = req.params;
  const row = await getExternalAuditorById(id);
  if (!row) {
    return res.status(404).json({ success: false, message: 'External auditor not found' });
  }
  res.status(200).json({ success: true, data: row });
});

// Create external auditor (e.g. from "Add new" popup)
exports.createExternalAuditor = asyncHandler(async (req, res) => {
  const { full_name, email, organization } = req.body;
  if (!full_name || String(full_name).trim() === '') {
    return res.status(400).json({ success: false, message: 'full_name is required' });
  }
  const id = await createExternalAuditor({ full_name, email, organization });
  if (!id) {
    return res.status(500).json({ success: false, message: 'Failed to create external auditor in database.' });
  }
  const created = await getExternalAuditorById(id);
  if (!created) {
    return res.status(500).json({ success: false, message: 'External auditor created but could not be retrieved.' });
  }
  res.status(201).json({ success: true, data: created });
});
