const db = require('../db/config');
const { Parser } = require('json2csv');
const { format } = require('fast-csv');

exports.downloadItemTemplate = async (req, res) => {
  try {
    const [categories] = await db.query('SELECT name FROM categories');
    const [brands] = await db.query('SELECT name FROM brands');

    const exampleData = [
      {
        name: 'Sample Item',
        sku: 'SKU123',
        unit: 'pcs',
        description: 'Sample description',
        quantity: 100,
        price: 50.00,
        min_qty: 10,
        category: categories[0]?.name || 'ExampleCategory',
        brand: brands[0]?.name || 'ExampleBrand'
      }
    ];

    const fields = [
      'name',
      'sku',
      'unit',
      'description',
      'quantity',
      'price',
      'min_qty',
      'category',
      'brand'
    ];

    const json2csv = new Parser({ fields });
    const csv = json2csv.parse(exampleData);

    res.header('Content-Type', 'text/csv');
    res.attachment('items-template.csv');
    return res.send(csv);
  } catch (err) {
    console.error(err);
    res.status(500).send('Failed to generate CSV template');
  }
};

exports.downloadCustomerTemplate = (req, res) => {
  try {
    res.setHeader('Content-Disposition', 'attachment; filename=customer-template.csv');
    res.setHeader('Content-Type', 'text/csv');

    const csvStream = format({ headers: true });

    csvStream.pipe(res);

    const sampleData = [
      { name: 'John Doe', email: 'john@example.com', phone: '1234567890', address: 'New York' },
      { name: 'Jane Smith', email: 'jane@example.com', phone: '9876543210', address: 'Los Angeles' },
      { name: 'Alice Brown', email: 'alice@domain.com', phone: '5556667777', address: 'Chicago' },
      { name: 'Bob Martin', email: 'bob@company.com', phone: '4445556666', address: 'Houston' }
    ];

    sampleData.forEach(row => csvStream.write(row));
    csvStream.end();

  } catch (err) {
    console.error('CSV Template Generation Error:', err);
    res.status(500).json({ error: 'Failed to generate CSV template.' });
  }
};