const express = require('express');
const router = express.Router();
const Deployment = require('../models/Deployment');

// Middleware to check if user is authenticated
const requireAuth = (req, res, next) => {
  if (!req.oidc.isAuthenticated()) {
    return res.status(401).json({ error: 'Authentication required' });
  }
  next();
};

// Get all deployments for the authenticated user
router.get('/', requireAuth, async (req, res) => {
  try {
    const deployments = await Deployment.find({ createdBy: req.oidc.user.sub })
      .sort({ createdAt: -1 });
    res.json(deployments);
  } catch (error) {
    console.error('Error fetching deployments:', error);
    res.status(500).json({ error: 'Failed to fetch deployments' });
  }
});

// Create a new deployment
router.post('/', requireAuth, async (req, res) => {
  try {
    const deployment = new Deployment({
      ...req.body,
      createdBy: req.oidc.user.sub
    });
    await deployment.save();
    res.status(201).json(deployment);
  } catch (error) {
    console.error('Error creating deployment:', error);
    res.status(500).json({ error: 'Failed to create deployment' });
  }
});

// Get a specific deployment
router.get('/:id', requireAuth, async (req, res) => {
  try {
    const deployment = await Deployment.findOne({
      _id: req.params.id,
      createdBy: req.oidc.user.sub
    });
    if (!deployment) {
      return res.status(404).json({ error: 'Deployment not found' });
    }
    res.json(deployment);
  } catch (error) {
    console.error('Error fetching deployment:', error);
    res.status(500).json({ error: 'Failed to fetch deployment' });
  }
});

// Update a deployment
router.put('/:id', requireAuth, async (req, res) => {
  try {
    const deployment = await Deployment.findOneAndUpdate(
      { _id: req.params.id, createdBy: req.oidc.user.sub },
      req.body,
      { new: true }
    );
    if (!deployment) {
      return res.status(404).json({ error: 'Deployment not found' });
    }
    res.json(deployment);
  } catch (error) {
    console.error('Error updating deployment:', error);
    res.status(500).json({ error: 'Failed to update deployment' });
  }
});

// Delete a deployment
router.delete('/:id', requireAuth, async (req, res) => {
  try {
    const deployment = await Deployment.findOneAndDelete({
      _id: req.params.id,
      createdBy: req.oidc.user.sub
    });
    if (!deployment) {
      return res.status(404).json({ error: 'Deployment not found' });
    }
    res.json({ message: 'Deployment deleted successfully' });
  } catch (error) {
    console.error('Error deleting deployment:', error);
    res.status(500).json({ error: 'Failed to delete deployment' });
  }
});

module.exports = router; 