/**
 * /api/admin/general  — Paramètres généraux de l'application
 * Protégé par requireAuth + requireAdmin (appliqués dans server.js).
 *
 * GET  /  — retourne les 4 champs généraux
 * PATCH / — met à jour un ou plusieurs champs
 *
 * Route publique complémentaire : /api/app-info (server.js) expose
 * allowRegistration et minPasswordLength sans auth.
 */

import { Router } from 'express';
import { z } from 'zod';
import db from '../db/index.js';

const router = Router();

function ensureRow() {
  const exists = db.prepare('SELECT id FROM smtp_config WHERE id = 1').get();
  if (!exists) {
    db.prepare(`
      INSERT INTO smtp_config (id, enabled, host, port, secure, email, username, password,
        allow_unauth, app_name, app_url, allow_registration, min_password_length)
      VALUES (1, 0, '', 587, 0, '', '', '', 0, 'Crowdlending Tracker', '', 1, 8)
    `).run();
  }
}

router.get('/', (_req, res, next) => {
  try {
    ensureRow();
    const row = db.prepare('SELECT app_name, app_url, allow_registration, min_password_length FROM smtp_config WHERE id = 1').get();
    res.json({
      appName:           row.app_name            || 'Crowdlending Tracker',
      appUrl:            row.app_url             || '',
      allowRegistration: row.allow_registration  !== 0,
      minPasswordLength: row.min_password_length || 8,
    });
  } catch (e) { next(e); }
});

const PatchSchema = z.object({
  appName:           z.string().min(1).max(100).optional(),
  appUrl:            z.string().max(500).optional(),
  allowRegistration: z.boolean().optional(),
  minPasswordLength: z.number().int().min(6).max(64).optional(),
});

router.patch('/', (req, res, next) => {
  try {
    ensureRow();
    const body = PatchSchema.parse(req.body);
    const row  = db.prepare('SELECT app_name, app_url, allow_registration, min_password_length FROM smtp_config WHERE id = 1').get();

    db.prepare(`
      UPDATE smtp_config SET
        app_name            = ?,
        app_url             = ?,
        allow_registration  = ?,
        min_password_length = ?
      WHERE id = 1
    `).run(
      body.appName           !== undefined ? body.appName                        : (row.app_name || 'Crowdlending Tracker'),
      body.appUrl            !== undefined ? body.appUrl                         : (row.app_url  || ''),
      body.allowRegistration !== undefined ? (body.allowRegistration ? 1 : 0)   : (row.allow_registration !== 0 ? 1 : 0),
      body.minPasswordLength !== undefined ? body.minPasswordLength              : (row.min_password_length || 8),
    );

    res.json({ ok: true });
  } catch (e) { next(e); }
});

export default router;
