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

// Получить все дополнительные сервисы (по УК)
router.get('/additional-services', async (req, res) => {
  const supabase = getSupabaseClient();
  const { management_company_id } = req.query;
  let query = supabase.from('additional_services').select('*');
  if (management_company_id) query = query.eq('management_company_id', management_company_id);
  const { data, error } = await query;
  if (error) return res.status(400).json({ error: error.message });
  res.json(data);
});

// Получить сервис по id
router.get('/additional-services/:id', async (req, res) => {
  const supabase = getSupabaseClient();
  const { id } = req.params;
  const { data, error } = await supabase.from('additional_services').select('*').eq('id', id).single();
  if (error) return res.status(400).json({ error: error.message });
  res.json(data);
});

// Создать сервис
router.post('/additional-services', async (req, res) => {
  const supabase = getSupabaseClient();
  const { title, description, category, price, image_url } = req.body;
  const { data, error } = await supabase.from('additional_services').insert([
    { title, description, category, price, image_url }
  ]).select().single();
  if (error) return res.status(400).json({ error: error.message });
  res.json(data);
});

// Обновить сервис
router.put('/additional-services/:id', async (req, res) => {
  const supabase = getSupabaseClient();
  const { id } = req.params;
  const { title, description, category, price, image_url } = req.body;
  const { data, error } = await supabase.from('additional_services').update({
    title, description, category, price, image_url
  }).eq('id', id).select().single();
  if (error) return res.status(400).json({ error: error.message });
  res.json(data);
});

// Удалить сервис
router.delete('/additional-services/:id', async (req, res) => {
  const supabase = getSupabaseClient();
  const { id } = req.params;
  const { error } = await supabase.from('additional_services').delete().eq('id', id);
  if (error) return res.status(400).json({ error: error.message });
  res.json({ success: true });
});

module.exports = router; 