const router = require('express').Router();
const { getSupabaseClient } = require('./supabaseClient');

// GET /profile
router.get('/profile', async (req, res) => {
  const { user_id } = req.query;
  const supabase = getSupabaseClient();
  let { data: userData, error: userError } = await supabase.auth.admin.getUserById(user_id);

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

  let { data: profileData, error: profileError } = await supabase.from('user_profiles').select(`
    id,
    full_name,
    avatar_url,
    updated_at
  `).eq('id', user_id).single();

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

  res.json({
    id: profileData.id,
    username: profileData.full_name,
    avatar_url: profileData.avatar_url,
    phone: userData.user.phone,
    updated_at: profileData.updated_at
  });
});

// POST /profile
router.post('/profile', async (req, res) => {
  const { user_id, data } = req.body;
  const supabase = getSupabaseClient();

  const { data: userData, error: userError } = await supabase.auth.admin.updateUserById(
    user_id,
    { phone: data.phone }
  )

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

  let { error: profileError } = await supabase.from('user_profiles').update({
    full_name: data.username,
    avatar_url: data.avatar_url,
    // apartment: data.apartment
  }).eq('id', user_id).single();

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

  res.json({ success: true });
});

// Получить управляющую компанию по квартире
router.get('/management-company', async (req, res) => {
  const supabase = getSupabaseClient();
  const { apartment_id } = req.query;
  if (!apartment_id) return res.status(400).json({ error: 'apartment_id required' });
  const { data: apartment, error: err1 } = await supabase.from('apartments').select('building_id').eq('id', apartment_id).single();
  if (err1) return res.status(400).json({ error: err1.message });
  const { data: building, error: err2 } = await supabase.from('buildings').select('management_company_id').eq('id', apartment.building_id).single();
  if (err2) return res.status(400).json({ error: err2.message });
  const { data: company, error: err3 } = await supabase.from('management_companies').select('*').eq('id', building.management_company_id).single();
  if (err3) return res.status(400).json({ error: err3.message });
  res.json(company);
});

module.exports = router; 