const express = require('express');
const router = express.Router();
const {
  getAllApplications,
  createApplication,
  updateApplication,
  deleteApplication
} = require('../config/db');

// GET /api/applications - Fetch all applications
router.get('/', async (req, res) => {
  try {
    const applications = await getAllApplications();
    res.json({ success: true, applications });
  } catch (error) {
    console.error('Error fetching applications:', error);
    res.status(500).json({ success: false, message: 'Failed to fetch applications' });
  }
});

// POST /api/applications - Create new application
router.post('/', async (req, res) => {
  try {
    const { name, category, product_code, url, buy_link, logo, description, status } = req.body;
    if (!name || !product_code) {
      return res.status(400).json({ success: false, message: 'Application Name and Product Code are required' });
    }

    const newApp = await createApplication({ name, category, product_code, url, buy_link, logo, description, status });
    res.status(201).json({ success: true, application: newApp });
  } catch (error) {
    console.error('Error creating application:', error);
    res.status(500).json({ success: false, message: 'Failed to create application', error: error.message });
  }
});

// PUT /api/applications/:id - Update existing application
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, category, product_code, url, buy_link, logo, description, status } = req.body;
    if (!name || !product_code) {
      return res.status(400).json({ success: false, message: 'Application Name and Product Code are required' });
    }

    const updated = await updateApplication(id, { name, category, product_code, url, buy_link, logo, description, status });
    res.json({ success: true, application: updated });
  } catch (error) {
    console.error('Error updating application:', error);
    res.status(500).json({ success: false, message: 'Failed to update application', error: error.message });
  }
});

// DELETE /api/applications/:id - Delete application
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    await deleteApplication(id);
    res.json({ success: true, message: 'Application deleted successfully' });
  } catch (error) {
    console.error('Error deleting application:', error);
    res.status(500).json({ success: false, message: 'Failed to delete application' });
  }
});

module.exports = router;
