const express = require('express');
const fs      = require('fs');
const path    = require('path');
const router  = express.Router();
const authMw  = require('../middleware/auth');

const CFG = path.join(__dirname, '../data/smtp.json');

function load() {
  if (!fs.existsSync(CFG)) return { host:'', port:587, secure:false, user:'', pass:'', from:'' };
  return JSON.parse(fs.readFileSync(CFG));
}
function save(c) {
  if (!fs.existsSync(path.dirname(CFG))) fs.mkdirSync(path.dirname(CFG), { recursive:true });
  fs.writeFileSync(CFG, JSON.stringify(c, null, 2));
}

router.get('/', authMw, (req, res) => {
  const c = load();
  res.json({ host:c.host, port:c.port, secure:c.secure, user:c.user, from:c.from, hasPass:!!c.pass });
});

router.post('/', authMw, (req, res) => {
  const { host, port, secure, user, pass, from } = req.body;
  const existing = load();
  save({ host, port:parseInt(port)||587, secure:!!secure, user, pass:pass||existing.pass, from });
  res.json({ ok:true });
});

router.post('/test', authMw, async (req, res) => {
  const c = load();
  if (!c.host) return res.status(400).json({ error:'SMTP not configured yet. Save settings first.' });
  if (!req.body.to) return res.status(400).json({ error:'Recipient email required' });
  try {
    const nm = require('nodemailer');
    const t  = nm.createTransport({ host:c.host, port:c.port, secure:c.secure, auth:c.user?{user:c.user,pass:c.pass}:undefined });
    await t.sendMail({ from:c.from||c.user, to:req.body.to, subject:'ServerPanel — Test Email', text:'This is a test email sent from your ServerPanel. If you received this, SMTP is configured correctly.' });
    res.json({ ok:true });
  } catch(e) { res.status(500).json({ error:e.message }); }
});

module.exports = router;