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/settings.json');

const DEFAULTS = {
  panelName:          'ServerPanel',
  timezone:           'UTC',
  crashMonitor:       true,
  crashEmailEnabled:  false,
  crashEmailTo:       '',
  crashEmailSubject:  'ServerPanel — System Crash Detected',
  sessionTimeout:     8,
  dateFormat:         'locale'
};

function load() {
  if (!fs.existsSync(CFG)) return { ...DEFAULTS };
  try { return { ...DEFAULTS, ...JSON.parse(fs.readFileSync(CFG, 'utf8')) }; }
  catch { return { ...DEFAULTS }; }
}

function save(s) {
  fs.mkdirSync(path.dirname(CFG), { recursive: true });
  fs.writeFileSync(CFG, JSON.stringify(s, null, 2));
}

router.get('/', authMw, (req, res) => {
  const cfg = load();
  // Include db cred metadata (no passwords) in main settings response
  const creds = loadDbCreds();
  res.json({
    ...cfg,
    dbMysqlHost: creds.mysqlHost, dbMysqlPort: creds.mysqlPort,
    dbMysqlUser: creds.mysqlUser, dbMysqlHasPass: !!creds.mysqlPass,
    dbPgHost: creds.pgHost, dbPgPort: creds.pgPort,
    dbPgUser: creds.pgUser, dbPgHasPass: !!creds.pgPass
  });
});

router.post('/', authMw, (req, res) => {
  if (req.user.role !== 'admin') return res.status(403).json({ error: 'Admin only' });
  const current = load();
  const updated = {
    ...current,
    panelName:         req.body.panelName         ?? current.panelName,
    timezone:          req.body.timezone          ?? current.timezone,
    crashMonitor:      req.body.crashMonitor      ?? current.crashMonitor,
    crashEmailEnabled: req.body.crashEmailEnabled ?? current.crashEmailEnabled,
    crashEmailTo:      req.body.crashEmailTo      ?? current.crashEmailTo,
    crashEmailSubject: req.body.crashEmailSubject ?? current.crashEmailSubject,
    sessionTimeout:    req.body.sessionTimeout    ?? current.sessionTimeout,
    dateFormat:        req.body.dateFormat        ?? current.dateFormat
  };
  save(updated);
  res.json({ ok: true });
});


// ── DB Credentials ─────────────────────────────────────
const DB_CRED = path.join(__dirname, '../data/db-credentials.json');

function loadDbCreds() {
  const defaults = {
    mysqlHost: 'localhost', mysqlPort: 3306, mysqlUser: 'root', mysqlPass: '',
    pgHost: 'localhost',    pgPort: 5432,    pgUser: 'postgres', pgPass: ''
  };
  try {
    if (!fs.existsSync(DB_CRED)) return defaults;
    return { ...defaults, ...JSON.parse(fs.readFileSync(DB_CRED, 'utf8')) };
  } catch { return defaults; }
}

router.get('/db-credentials', authMw, (req, res) => {
  if (req.user.role !== 'admin') return res.status(403).json({ error: 'Admin only' });
  const c = loadDbCreds();
  // Never return actual passwords — just whether they are set
  res.json({
    dbMysqlHost: c.mysqlHost, dbMysqlPort: c.mysqlPort, dbMysqlUser: c.mysqlUser,
    dbMysqlHasPass: !!c.mysqlPass,
    dbPgHost: c.pgHost, dbPgPort: c.pgPort, dbPgUser: c.pgUser,
    dbPgHasPass: !!c.pgPass
  });
});

router.post('/db-credentials', authMw, (req, res) => {
  if (req.user.role !== 'admin') return res.status(403).json({ error: 'Admin only' });
  const existing = loadDbCreds();
  const updated = {
    mysqlHost: req.body.dbMysqlHost ?? existing.mysqlHost,
    mysqlPort: req.body.dbMysqlPort ?? existing.mysqlPort,
    mysqlUser: req.body.dbMysqlUser ?? existing.mysqlUser,
    mysqlPass: req.body.dbMysqlPass ?? existing.mysqlPass, // null means keep existing
    pgHost:    req.body.dbPgHost    ?? existing.pgHost,
    pgPort:    req.body.dbPgPort    ?? existing.pgPort,
    pgUser:    req.body.dbPgUser    ?? existing.pgUser,
    pgPass:    req.body.dbPgPass    ?? existing.pgPass
  };
  // If password sent as null/empty string and existing has one, keep existing
  if (!req.body.dbMysqlPass && existing.mysqlPass) updated.mysqlPass = existing.mysqlPass;
  if (!req.body.dbPgPass    && existing.pgPass)    updated.pgPass    = existing.pgPass;
  try {
    fs.mkdirSync(path.dirname(DB_CRED), { recursive: true });
    fs.writeFileSync(DB_CRED, JSON.stringify(updated, null, 2));
    res.json({ ok: true });
  } catch(e) { res.status(500).json({ error: e.message }); }
});

module.exports = router;
module.exports.load = load;
module.exports.loadDbCreds = loadDbCreds;