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

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

  // Получаем все платежки по квартире
  const { data: services, error: servicesError } = await supabase
    .from('payment_services')
    .select('id, name, icon, amount, is_paid, payment_method')
    .eq('apartment_id', apartment_id);
  if (servicesError) return res.status(400).json({ error: servicesError.message });

  // Получаем детализацию по всем платежкам
  const serviceIds = services.map(s => s.id);
  let details = [];
  if (serviceIds.length > 0) {
    const { data: detailsData, error: detailsError } = await supabase
      .from('payment_service_details')
      .select('id, payment_service_id, name, amount')
      .in('payment_service_id', serviceIds);
    if (detailsError) return res.status(400).json({ error: detailsError.message });
    details = detailsData;
  }

  // Формируем структуру для фронта
  const result = services.map(service => {
    const serviceDetails = details.filter(d => d.payment_service_id === service.id).map(detail => ({
      id: detail.id,
      name: detail.name,
      amount: detail.amount
    }));
    return {
      id: service.id,
      title: service.name,
      icon: service.icon,
      amount: service.amount,
      isPaid: service.is_paid,
      paymentMethod: service.payment_method,
      details: serviceDetails
    };
  });

  res.json(result);
});

module.exports = router;