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

async function getAlertsForUser(userId) {
  const supabase = getSupabaseServiceClient();

  const { data: alerts, error } = await supabase
    .from('cascade_alerts')
    .select('*')
    .eq('user_id', userId)
    .eq('is_read', false)
    .order('created_at', { ascending: false });

  if (error) throw error;

  const { count } = await supabase
    .from('cascade_alerts')
    .select('*', { count: 'exact', head: true })
    .eq('user_id', userId)
    .eq('is_read', false);

  return { alerts: alerts || [], unread_count: count || (alerts || []).length };
}

async function markAlertRead(alertId, userId) {
  const supabase = getSupabaseServiceClient();

  const { data, error } = await supabase
    .from('cascade_alerts')
    .update({ is_read: true })
    .eq('id', alertId)
    .eq('user_id', userId)
    .select('id, is_read')
    .single();

  if (error || !data) return null;
  return data;
}

module.exports = { getAlertsForUser, markAlertRead };
