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

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

  try {
    const { error } = await supabase
      .from('deployments')
      .update({
        alarm_on: alarm_on === '1' || alarm_on === 1,
        time_edit: Date.now() / 1000
      })
      .eq('deployment_id', deployment_id);

    if (error) throw error;

    return res.json({
      success: true,
      deployment_id,
      alarm_on: alarm_on === '1' || alarm_on === 1
    });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};

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

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

    if (error) throw error;

    return res.json({
      deployment_id,
      alarm_on: data?.alarm_on || false,
      alarm_details: data?.alarm_details || null
    });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};

// POST: store_alarms
exports.store = async (req, res) => {
  const {
    user_name, token, deployment_id, deployment_alarms,
    device_id, device_alarms
  } = req.body;

  try {
    // Store deployment alarms
    if (deployment_id && deployment_alarms) {
      await supabase
        .from('deployments')
        .update({
          alarm_details: JSON.parse(deployment_alarms),
          time_edit: Date.now() / 1000
        })
        .eq('deployment_id', deployment_id);
    }

    // Store device alarms
    if (device_id && device_alarms) {
      await supabase
        .from('devices')
        .update({
          alarm_settings: JSON.parse(device_alarms),
          time_edit: Date.now() / 1000
        })
        .eq('device_id', device_id);
    }

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

// POST: send_walarm
exports.sendWalarm = async (req, res) => {
  const {
    user_name, token, deployment_id,
    location, method, conditionType, content
  } = req.body;

  try {
    // TODO: Implement alarm sending (push notifications, SMS, etc.)
    // For now, log the alarm and return success

    console.log('ALARM:', {
      deployment_id,
      location,
      method,
      conditionType,
      content,
      timestamp: new Date().toISOString()
    });

    return res.json({
      success: true,
      message: 'Alarm sent',
      deployment_id
    });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};

// POST: activity_detected
exports.activityDetected = async (req, res) => {
  const { user_name, token, time, deployment_id, device_id } = req.body;

  try {
    // Log activity detection
    // TODO: Store in activity_log table

    return res.json({
      success: true,
      time,
      deployment_id,
      device_id
    });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};
