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

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

  try {
    const { data, error, count } = await supabase
      .from('person_details')
      .select('*', { count: 'exact' })
      .eq('role', 'beneficiary')
      .range(parseInt(first), parseInt(last) - 1);

    if (error) throw error;

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

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

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

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

// POST: beneficiary_form - create/update beneficiary
exports.form = async (req, res) => {
  const {
    user_name, token, new_user_name, editing_user_id, user_id,
    role_ids, email, first_name, last_name,
    address_street, address_city, address_zip, address_state, address_country,
    phone_number, picture, key
  } = req.body;

  try {
    const personData = {
      username: new_user_name,
      email,
      first_name,
      last_name,
      address_street,
      address_city,
      address_zip,
      address_state,
      address_country,
      phone_number,
      picture,
      role: 'beneficiary',
      role_ids: role_ids ? JSON.parse(role_ids) : null,
      time_edit: Date.now() / 1000
    };

    let result;
    const id = editing_user_id || user_id;

    if (id) {
      // Update existing
      const { data, error } = await supabase
        .from('person_details')
        .update(personData)
        .eq('person_id', id)
        .select()
        .single();

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

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

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