const express = require('express');
const router = express.Router();
const pm = require('../services/project-manager');
const fs = require('fs');
const path = require('path');

const DATA_DIR = path.join(__dirname, '..', 'data');

function ensureDir(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}

router.get('/', (req, res) => {
  const projects = pm.getAll();
  const projectId = req.query.project || (projects.length > 0 ? projects[0].id : null);
  const project = projects.find(p => p.id === projectId);

  const dataFiles = [];
  if (fs.existsSync(DATA_DIR)) {
    fs.readdirSync(DATA_DIR).forEach(f => {
      const fp = path.join(DATA_DIR, f);
      dataFiles.push({ name: f, size: fs.statSync(fp).size, modified: fs.statSync(fp).mtime });
    });
  }

  let testSpecs = [];
  let testPlans = [];
  if (project) {
    const bridge = pm.getBridge(project.id);
    testSpecs = bridge.listTestSpecs().map(specName => ({
      name: specName,
      content: bridge.getSpecContent(specName),
    }));
    testPlans = bridge.listTestPlans().map(planName => ({
      name: planName,
      content: bridge.getPlanContent(planName),
    }));
  }

  res.render('test-data', { project, projects, dataFiles, testSpecs, testPlans });
});

router.get('/spec/:specName', (req, res) => {
  const projects = pm.getAll();
  const projectId = req.query.project || (projects.length > 0 ? projects[0].id : null);
  const project = projects.find(p => p.id === projectId);
  if (!project) return res.status(404).send('Project not found');

  const bridge = pm.getBridge(project.id);
  const content = bridge.getSpecContent(req.params.specName);
  if (!content) return res.status(404).send('Spec not found');

  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  res.setHeader('Content-Disposition', `attachment; filename="${req.params.specName}"`);
  res.send(content);
});

router.get('/plan/:planName', (req, res) => {
  const projects = pm.getAll();
  const projectId = req.query.project || (projects.length > 0 ? projects[0].id : null);
  const project = projects.find(p => p.id === projectId);
  if (!project) return res.status(404).send('Project not found');

  const bridge = pm.getBridge(project.id);
  const content = bridge.getPlanContent(req.params.planName);
  if (!content) return res.status(404).send('Plan not found');

  res.setHeader('Content-Type', 'text/markdown; charset=utf-8');
  res.setHeader('Content-Disposition', `attachment; filename="${req.params.planName}"`);
  res.send(content);
});

router.post('/generate', (req, res) => {
  const { type, count } = req.body;
  const num = parseInt(count) || 5;

  ensureDir(DATA_DIR);

  if (type === 'users') {
    const users = [];
    for (let i = 0; i < num; i++) {
      users.push({
        id: `user_${i + 1}`,
        name: `Test User ${i + 1}`,
        email: `testuser${i + 1}@test.com`,
        phone: `060000${String(i + 1).padStart(4, '0')}`,
        role: i % 2 === 0 ? 'admin' : 'user',
        createdAt: new Date().toISOString(),
      });
    }
    const filePath = path.join(DATA_DIR, `test-users-${Date.now()}.json`);
    fs.writeFileSync(filePath, JSON.stringify(users, null, 2));
    res.json({ success: true, file: path.basename(filePath), count: num });
  } else if (type === 'transactions') {
    const txns = [];
    const amounts = [25, 50, 75, 100, 150, 200];
    for (let i = 0; i < num; i++) {
      txns.push({
        id: `TXN${String(i + 1).padStart(6, '0')}`,
        amount: amounts[Math.floor(Math.random() * amounts.length)],
        currency: 'EUR',
        status: ['completed', 'pending', 'failed'][Math.floor(Math.random() * 3)],
        sender: `user_${Math.floor(Math.random() * 10) + 1}`,
        recipient: `user_${Math.floor(Math.random() * 10) + 11}`,
        timestamp: new Date(Date.now() - Math.random() * 86400000 * 30).toISOString(),
      });
    }
    const filePath = path.join(DATA_DIR, `test-transactions-${Date.now()}.json`);
    fs.writeFileSync(filePath, JSON.stringify(txns, null, 2));
    res.json({ success: true, file: path.basename(filePath), count: num });
  } else {
    res.json({ success: false, error: 'Unknown data type. Use: users, transactions' });
  }
});

router.delete('/:file', (req, res) => {
  const filePath = path.join(DATA_DIR, req.params.file);
  if (fs.existsSync(filePath)) {
    fs.unlinkSync(filePath);
    res.json({ success: true });
  } else {
    res.json({ success: false, error: 'File not found' });
  }
});

module.exports = router;