import { objectSchema } from '../../kernel/input-schema.mjs';
import { getSettingsService } from './index.mjs';

const smtpSchema = objectSchema({
  smtp_host: { type: 'string', maxLength: 255 }, smtp_port: { type: 'string', maxLength: 8 },
  smtp_user: { type: 'string', maxLength: 255 }, smtp_pass: { type: 'string', maxLength: 4096, trim: false },
  smtp_from: { type: 'string', maxLength: 255 },
});

export function registerSettingsRoutes({ app, routes, deps }) {
  routes.register(app, {
    id: 'settings.application.read', method: 'GET', path: '/api/settings', owner: 'vendoo.settings', policy: 'settings.read', csrf: false, stability: 'stable',
    handler: async (_req, res) => res.json(getSettingsService().get()),
  });
  routes.register(app, {
    id: 'settings.application.update', method: 'PUT', path: '/api/settings', owner: 'vendoo.settings', policy: 'settings.manage', csrf: true, stability: 'stable',
    handler: async (req, res) => {
      const result = getSettingsService().update(req.body || {});
      deps.auditLog(req.user.id, req.user.email, 'settings.updated', 'settings', 'application', null, deps.getClientIp(req));
      res.json(result);
    },
  });
  routes.register(app, {
    id: 'settings.smtp.read', method: 'GET', path: '/api/admin/smtp', owner: 'vendoo.settings', policy: 'settings.manage', csrf: false, stability: 'stable',
    handler: async (_req, res) => res.json(getSettingsService().smtpStatus()),
  });
  routes.register(app, {
    id: 'settings.smtp.update', method: 'PUT', path: '/api/admin/smtp', owner: 'vendoo.settings', policy: 'settings.manage', csrf: true, stability: 'stable', input: smtpSchema,
    handler: async (req, res) => {
      const result = getSettingsService().updateSmtp(req.validatedBody || {});
      deps.auditLog(req.user.id, req.user.email, 'smtp.updated', 'settings', 'smtp', null, deps.getClientIp(req));
      res.json(result);
    },
  });
  routes.register(app, {
    id: 'settings.smtp.test', method: 'POST', path: '/api/admin/smtp/test', owner: 'vendoo.settings', policy: 'settings.manage', csrf: true, stability: 'stable',
    handler: async (req, res) => {
      if (!deps.isMailerConfigured()) return res.status(400).json({ error: 'SMTP nicht konfiguriert. Bitte zuerst speichern.' });
      if (!req.user?.email) return res.status(400).json({ error: 'Admin-E-Mail nicht gefunden' });
      await deps.testMailer(req.user.email);
      deps.auditLog(req.user.id, req.user.email, 'smtp.test_sent', 'settings', 'smtp', `an ${req.user.email}`, deps.getClientIp(req));
      res.json({ ok: true, message: `Testmail an ${req.user.email} gesendet` });
    },
  });
}
