const express = require('express');
const router = express.Router();
const Deployment = require('../models/Deployment');
const { checkAdminRole } = require('../middleware/auth');

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

// Add this helper function
const isSubdomainAvailable = async (subdomain, excludeId = null) => {
  const query = { 
    subdomain,
    useWildcard: true
  };
  
  // If we're updating, exclude the current deployment
  if (excludeId) {
    query._id = { $ne: excludeId };
  }
  
  const existing = await Deployment.findOne(query);
  return !existing;
};

// Create a new deployment
router.post('/', requireAuth, async (req, res) => {
  try {
    console.log('Request body:', req.body);
    console.log('User:', req.oidc.user);
    
    // 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(', ')}`
      });
    }

    // Check if subdomain is available
    if (req.body.useWildcard && req.body.subdomain) {
      const isAvailable = await isSubdomainAvailable(req.body.subdomain);
      if (!isAvailable) {
        return res.status(400).json({
          error: 'Validation error',
          details: 'This subdomain is already in use'
        });
      }
    }

    // Create deployment data
    const deploymentData = {
      name: req.body.name,
      sourceType: req.body.sourceType,
      gitUrl: req.body.gitUrl,
      containerImage: req.body.containerImage,
      template: req.body.template,
      regions: req.body.regions,
      domain: req.body.domain,
      useWildcard: req.body.useWildcard,
      subdomain: req.body.subdomain,
      env: req.body.env || [],
      resources: req.body.resources || {
        cpu: 0.5,
        memory: '512Mi'
      },
      createdBy: req.oidc.user.sub,
      status: 'deploying'
    };

    const deployment = new Deployment(deploymentData);
    const savedDeployment = await deployment.save();
    
    res.status(201).json(savedDeployment);
  } catch (error) {
    console.error('Error creating deployment:', error);
    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 {
    // Check subdomain availability if changing to wildcard domain
    if (req.body.useWildcard && req.body.subdomain) {
      const isAvailable = await isSubdomainAvailable(req.body.subdomain, req.params.id);
      if (!isAvailable) {
        return res.status(400).json({
          error: 'Validation error',
          details: 'This subdomain is already in use'
        });
      }
    }

    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' });
  }
});

// Add middleware to check regions in deployment requests
router.post('/deployments', async (req, res) => {
  const { regions } = req.body;
  const roles = req.user['https://container-mom.com/roles'] || [];
  
  // Check if non-admin tries to use test region
  if (regions.includes('test') && !roles.includes('admin')) {
    return res.status(403).json({
      error: 'Forbidden',
      details: 'Test region is only available to administrators'
    });
  }
  
  // ... rest of the deployment creation logic
});

module.exports = router; 