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

// Получить все квартиры по дому
router.get('/apartments', async (req, res) => {
  const supabase = getSupabaseClient();
  const { building_id } = req.query;
  if (!building_id) return res.status(400).json({ error: 'building_id required' });
  const { data, error } = await supabase.from('apartments').select('*').eq('building_id', building_id);
  if (error) return res.status(400).json({ error: error.message });
  res.json(data);
});

// Получить адрес квартиры и название дома по id квартиры
router.get('/apartment-info', async (req, res) => {
  const supabase = getSupabaseClient();
  const { apartment_id } = req.query;
  if (!apartment_id) return res.status(400).json({ error: 'apartment_id required' });

  // Получаем квартиру с building_id и номером
  const { data: apartment, error: err1 } = await supabase
    .from('apartments')
    .select('id, number, building_id')
    .eq('id', apartment_id)
    .single();
  if (err1) return res.status(400).json({ error: err1.message });

  // Получаем дом по building_id
  const { data: building, error: err2 } = await supabase
    .from('buildings')
    .select('id, name, address')
    .eq('id', apartment.building_id)
    .single();
  if (err2) return res.status(400).json({ error: err2.message });

  res.json({
    apartment_id: apartment.id,
    apartment_number: apartment.number,
    building_id: building.id,
    building_name: building.name,
    building_address: building.address
  });
});

module.exports = router; 