// routes/data.js
const express = require('express');
const mongoose = require('mongoose');
const { verifyToken } = require('./auth');

const router = express.Router();

// Dynamic model cache
const models = {};

// Get or create model for data type
const getModel = (type) => {
  if (!models[type]) {
    const schema = new mongoose.Schema({}, { strict: false }); // Flexible schema for app data
    models[type] = mongoose.model(type, schema, type); // Collection name = type
  }
  return models[type];
};

// Get all items for type
router.get('/:type', verifyToken, async (req, res) => {
  try {
    const Model = getModel(req.params.type);
    const items = await Model.find();
    res.json(items);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

// Create new item
router.post('/:type', verifyToken, async (req, res) => {
  try {
    const Model = getModel(req.params.type);
    const item = new Model(req.body);
    await item.save();
    res.status(201).json(item);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// Update item by ID
router.put('/:type/:id', verifyToken, async (req, res) => {
  try {
    const Model = getModel(req.params.type);
    const item = await Model.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!item) return res.status(404).json({ error: 'Not found' });
    res.json(item);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

// Delete item by ID
router.delete('/:type/:id', verifyToken, async (req, res) => {
  try {
    const Model = getModel(req.params.type);
    const item = await Model.findByIdAndDelete(req.params.id);
    if (!item) return res.status(404).json({ error: 'Not found' });
    res.json({ message: 'Deleted' });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;