'use strict';

const express = require('express');
const router  = express.Router();
const { getDb } = require('../db/database');
const { seedDemoData } = require('../scripts/seedDemoData');
const { demoDataLimiter } = require('../middleware/rateLimiter');

// POST /api/user/clear-demo-data — removes all seeded bills and categories for the requesting user
router.post('/clear-demo-data', demoDataLimiter, (req, res) => {
  try {
    const db = getDb();
    const userId = req.user.id;
    
    // Delete seeded bills
    const billsResult = db.prepare('DELETE FROM bills WHERE user_id = ? AND is_seeded = 1').run(userId);
    const billsDeleted = billsResult.changes;
    
    // Delete seeded categories
    const categoriesResult = db.prepare('DELETE FROM categories WHERE user_id = ? AND is_seeded = 1').run(userId);
    const categoriesDeleted = categoriesResult.changes;
    
    // Audit logging: record the clear action to import_history
    db.prepare(
      `INSERT INTO import_history (user_id, imported_at, source_filename, file_type, rows_parsed, rows_created, rows_updated, rows_skipped, rows_ambiguous, rows_errored, options_json, summary_json)
       VALUES (?, datetime('now'), ?, 'clear-demo', ?, 0, 0, 0, 0, 0, ?, ?)`
    ).run(userId, 'clear-demo-data', billsDeleted + categoriesDeleted, JSON.stringify({ action: 'clear-demo-data', userId }), JSON.stringify({ bills_deleted: billsDeleted, categories_deleted: categoriesDeleted }));
    
    res.json({
      success: true,
      billsDeleted,
      categoriesDeleted,
    });
  } catch (err) {
    const status = err.status || 500;
    res.status(status).json({ error: status === 500 ? 'Clear demo data operation failed' : err.message });
  }
});

// POST /api/user/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;
