'use strict';

const express = require('express');
const router  = express.Router();
const { getDb, getSetting, setSetting } = require('../db/database');
const { seedDemoData } = require('../scripts/seedDemoData');

// Keys a regular user is allowed to read and write.
// Admin/SMTP/backup/auth settings are excluded — they are only readable through
// their respective admin endpoints and never exposed here.
const USER_SETTING_KEYS = [
  'currency', 'date_format', 'grace_period_days', 'notify_days_before',
];

// GET /api/settings — returns only user-facing app preferences
router.get('/', (req, res) => {
  const db       = getDb();
  const settings = {};
  for (const key of USER_SETTING_KEYS) {
    const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key);
    if (row) settings[key] = row.value;
  }
  res.json(settings);
});

// PUT /api/settings — updates only allowed user-facing keys; silently ignores others
router.put('/', (req, res) => {
  for (const [key, value] of Object.entries(req.body)) {
    if (USER_SETTING_KEYS.includes(key)) setSetting(key, value);
  }

  const db       = getDb();
  const settings = {};
  for (const key of USER_SETTING_KEYS) {
    const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key);
    if (row) settings[key] = row.value;
  }
  res.json(settings);
});

// POST /api/settings/seed-demo-data — seeds 20 demo bills for the requesting user
router.post('/seed-demo-data', (req, res) => {
  try {
    const result = seedDemoData(req.user.id);
    res.json({
      success: true,
      message: `Created ${result.billsCreated} demo bills and ${result.categoriesCreated} demo categories`,
      billsCreated: result.billsCreated,
      categoriesCreated: result.categoriesCreated,
    });
  } catch (err) {
    const status = err.status || 500;
    res.status(status).json({ error: status === 500 ? 'Seed operation failed' : err.message });
  }
});

module.exports = router;
