'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');
const { eraseUserData } = require('../services/userDataService');
const { standardizeError } = require('../middleware/errorFormatter');

// GET /api/user/seeded-status — returns whether the current user has any seeded data
router.get('/seeded-status', (req, res) => {
  try {
    const db = getDb();
    const userId = req.user.id;
    
    // Check for seeded bills
    const seededBillsResult = db.prepare('SELECT COUNT(*) as count FROM bills WHERE user_id = ? AND is_seeded = 1').get(userId);
    const seededBillsCount = seededBillsResult.count;
    
    // Check for seeded categories
    const seededCategoriesResult = db.prepare('SELECT COUNT(*) as count FROM categories WHERE user_id = ? AND is_seeded = 1').get(userId);
    const seededCategoriesCount = seededCategoriesResult.count;
    
    const hasSeededData = seededBillsCount > 0 || seededCategoriesCount > 0;
    
    res.json({
      seeded: hasSeededData,
      seededBills: seededBillsCount,
      seededCategories: seededCategoriesCount,
    });
  } catch (err) {
    const status = err.status || 500;
    res.status(status).json({ error: status === 500 ? 'Seeded status check failed' : err.message });
  }
});

// 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 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 });
  }
});

// POST /api/user/erase-data — permanently wipe the requesting user's financial +
// imported data (bills, payments, transactions, connections, categories, imports).
// Preserves the account, login, 2FA, and preferences. Requires a type-to-confirm token.
router.post('/erase-data', demoDataLimiter, (req, res) => {
  const confirm = String(req.body?.confirm ?? '').trim().toUpperCase();
  if (confirm !== 'ERASE') {
    return res.status(400).json(standardizeError('Type ERASE to confirm.', 'ERASE_CONFIRM_REQUIRED', 'confirm'));
  }
  try {
    const result = eraseUserData(getDb(), req.user.id);
    res.json({ success: true, ...result });
  } catch (err) {
    res.status(err.status || 500).json(standardizeError(err.message || 'Failed to erase data', err.code || 'ERASE_ERROR'));
  }
});

module.exports = router;
