const { supabase } = require('../config/supabase');
const { verifyToken } = require('../middleware/auth');

// POST: dashboard_list - get all deployments for dashboard
exports.list = async (req, res) => {
  const { user_name, token, user_id, date } = req.body;

  try {
    // Get all deployments
    const { data: deployments, error } = await supabase
      .from('deployments')
      .select('*')
      .order('deployment_id', { ascending: true });

    if (error) {
      return res.status(500).json({ error: error.message });
    }

    return res.json(deployments);

  } catch (error) {
    console.error('Dashboard list error:', error);
    return res.status(500).json({ error: error.message });
  }
};

// POST: dashboard_single - get single deployment details
exports.single = async (req, res) => {
  const { user_name, token, date, deployment_id, nonce } = req.body;

  try {
    // Get deployment
    const { data: deployment, error } = await supabase
      .from('deployments')
      .select('*')
      .eq('deployment_id', deployment_id)
      .single();

    if (error) {
      return res.status(404).json({ error: 'Deployment not found' });
    }

    // Get devices for this deployment
    const { data: devices } = await supabase
      .from('devices')
      .select('*')
      .eq('deployment_id', deployment_id);

    // Get deployment details
    const { data: details } = await supabase
      .from('deployment_details')
      .select('*')
      .eq('deployment_id', deployment_id)
      .single();

    return res.json({
      deployment,
      devices: devices || [],
      details: details || null
    });

  } catch (error) {
    console.error('Dashboard single error:', error);
    return res.status(500).json({ error: error.message });
  }
};
