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

// POST: deployments_list
exports.list = async (req, res) => {
  const { user_name, token, first = 0, last = 100 } = req.body;

  try {
    const { data, error, count } = await supabase
      .from('deployments')
      .select('*', { count: 'exact' })
      .range(parseInt(first), parseInt(last) - 1)
      .order('deployment_id', { ascending: true });

    if (error) throw error;

    return res.json({
      deployments: data,
      total: count
    });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};

// POST: get_deployment
exports.get = async (req, res) => {
  const { user_name, token, date, deployment_id } = req.body;

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

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

// POST: deployment_form - create/update deployment
exports.form = async (req, res) => {
  const {
    user_name, token, editing_deployment_id,
    beneficiary_id, caretaker_id, owner_id, installer_id,
    address_street, address_city, address_zip, address_state, address_country,
    persons, gender, race, born, pets, wifis,
    lat, lng, devices, time_zone_s
  } = req.body;

  try {
    const deploymentData = {
      time_edit: Date.now() / 1000,
      user_edit: 1, // TODO: get from token
      time_zone_s,
      persons: parseInt(persons) || 0,
      gender: parseInt(gender) || 0,
      race: parseInt(race) || 0,
      born: parseInt(born) || null,
      pets: parseInt(pets) || 0
    };

    let result;
    if (editing_deployment_id) {
      // Update existing
      const { data, error } = await supabase
        .from('deployments')
        .update(deploymentData)
        .eq('deployment_id', editing_deployment_id)
        .select()
        .single();

      if (error) throw error;
      result = data;
    } else {
      // Create new
      const { data, error } = await supabase
        .from('deployments')
        .insert(deploymentData)
        .select()
        .single();

      if (error) throw error;
      result = data;
    }

    return res.json({ success: true, deployment: result });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};

// POST: deployment_delete
exports.delete = async (req, res) => {
  const { user_name, token, editing_deployment_id } = req.body;

  try {
    const { error } = await supabase
      .from('deployments')
      .delete()
      .eq('deployment_id', editing_deployment_id);

    if (error) throw error;
    return res.json({ success: true });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};

// POST: set_deployment
exports.set = async (req, res) => {
  // Same as form but with different field names
  return exports.form(req, res);
};

// POST: find_deployments
exports.find = async (req, res) => {
  const { user_name, token, well_ids } = req.body;

  try {
    const ids = well_ids.split(',').map(id => id.trim());

    const { data, error } = await supabase
      .from('deployments')
      .select('*')
      .in('deployment_id', ids);

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

// POST: get_floor_layout
exports.getFloorLayout = async (req, res) => {
  const { user_name, token, deployment_id } = req.body;

  try {
    const { data, error } = await supabase
      .from('deployment_details')
      .select('floor_layout')
      .eq('deployment_id', deployment_id)
      .single();

    if (error) throw error;
    return res.json({ layout: data?.floor_layout || null });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};

// POST: set_floor_layout
exports.setFloorLayout = async (req, res) => {
  const { user_name, token, deployment_id, layout } = req.body;

  try {
    const { error } = await supabase
      .from('deployment_details')
      .upsert({
        deployment_id,
        floor_layout: layout
      });

    if (error) throw error;
    return res.json({ success: true });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};

// POST: request_deployment_map_new
exports.requestMap = async (req, res) => {
  const { user_name, token, deployment_id, map_type } = req.body;

  try {
    // Return map data from deployment_details
    const { data, error } = await supabase
      .from('deployment_details')
      .select('*')
      .eq('deployment_id', deployment_id)
      .single();

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