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

// POST: caretakers_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', 'caretaker')
      .range(parseInt(first), parseInt(last) - 1);

    if (error) throw error;

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

// POST: get_caretaker
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: 'Caretaker not found' });
  }
};

// POST: caretaker_form - create/update caretaker
exports.form = async (req, res) => {
  const {
    user_name, token, new_user_name, user_id, editing_user_id, key,
    role_ids, access_to, email, first_name, last_name,
    address_street, address_city, address_zip, address_state, address_country,
    phone_number, picture
  } = 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: 'caretaker',
      role_ids: role_ids ? JSON.parse(role_ids) : null,
      access_to: access_to ? JSON.parse(access_to) : 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, caretaker: result });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};
