import { supabase } from "@/integrations/supabase/client";

export type NotificationCategory =
  | "messages_comments"
  | "financial"
  | "governance"
  | "compliance";

export const NOTIFICATION_CATEGORY_LABELS: Record<NotificationCategory, string> = {
  messages_comments: "Messages & Comments",
  financial: "Bills, Invoices & Payments",
  governance: "Board Votes, Announcements & Meetings",
  compliance: "Violations, ARC & Work Orders",
};

export const NOTIFICATION_CATEGORY_DESCRIPTIONS: Record<NotificationCategory, string> = {
  messages_comments: "Direct messages, comment replies, and mentions",
  financial: "New bills, payment reminders, and receipts",
  governance: "Voting requests, announcements, agendas, and minutes",
  compliance: "Violation notices, ARC decisions, and work order updates",
};

export const DEFAULT_NOTIFICATION_PREFERENCES: Record<NotificationCategory, boolean> = {
  messages_comments: true,
  financial: true,
  governance: true,
  compliance: true,
};

/**
 * Returns whether a given user wants email notifications for a category.
 * Defaults to `true` if the user has no preferences set.
 */
export async function shouldNotifyUser(
  userId: string,
  category: NotificationCategory
): Promise<boolean> {
  if (!userId) return false;
  try {
    const { data, error } = await supabase
      .from("profiles")
      .select("notification_preferences")
      .eq("user_id", userId)
      .maybeSingle();
    if (error || !data) return true;
    const prefs = (data.notification_preferences ?? {}) as Record<string, boolean>;
    return prefs[category] !== false;
  } catch {
    return true;
  }
}

/**
 * Returns the preferred notification email for a user, falling back to their primary email.
 */
export async function getPreferredNotificationEmail(
  userId: string
): Promise<string | null> {
  if (!userId) return null;
  const { data } = await supabase
    .from("profiles")
    .select("preferred_notification_email, email")
    .eq("user_id", userId)
    .maybeSingle();
  if (!data) return null;
  return data.preferred_notification_email || data.email || null;
}
