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',
      details: error.message 
    });
  }
});

// Create a new deployment
router.post('/', requireAuth, async (req, res) => {
  try {
    console.log('Received deployment data:', req.body);
    
    // Validate required fields
    const requiredFields = ['name', 'sourceType', 'regions', 'domain'];
    const missingFields = requiredFields.filter(field => !req.body[field]);
    
    if (missingFields.length > 0) {
      return res.status(400).json({
        error: 'Missing required fields',
        details: `Missing fields: ${missingFields.join(', ')}`
      });
    }

    // Validate source based on sourceType
    if (req.body.sourceType === 'git' && !req.body.gitUrl) {
      return res.status(400).json({
        error: 'Invalid source',
        details: 'Git URL is required for git source type'
      });
    }

    if (req.body.sourceType === 'container' && !req.body.containerImage) {
      return res.status(400).json({
        error: 'Invalid source',
        details: 'Container image is required for container source type'
      });
    }

    const deploymentData = {
      ...req.body,
      createdBy: req.oidc.user.sub,
      status: 'deploying'
    };

    console.log('Creating deployment with data:', deploymentData);

    const deployment = new Deployment(deploymentData);
    await deployment.save();

    console.log('Created deployment:', deployment);
    
    res.status(201).json(deployment);
  } catch (error) {
    console.error('Error creating deployment:', error);
    
    // Handle Mongoose validation errors
    if (error.name === 'ValidationError') {
      return res.status(400).json({
        error: 'Validation error',
        details: Object.values(error.errors).map(err => err.message).join(', ')
      });
    }

    res.status(500).json({ 
      error: 'Failed to create deployment',
      details: error.message 
    });
  }
});

// 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; 