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

interface ArcNotifyArgs {
  applicationId: string;
  applicationTitle: string;
  homeownerName?: string;
  associationId?: string | null;
  associationName?: string;
  propertyAddress?: string;
  projectType?: string | null;
  description?: string | null;
  fileCount?: number;
}

/**
 * Notify all admin/manager staff that a new ARC application was submitted.
 * Fire-and-forget: errors are logged but do not throw.
 */
export async function notifyStaffOfArcSubmission(args: ArcNotifyArgs): Promise<void> {
  try {
    // Look up staff users (admin + manager roles)
    const { data: staffRoles } = await supabase
      .from("user_roles")
      .select("user_id")
      .in("role", ["admin", "manager"]);

    const staffUserIds = Array.from(
      new Set((staffRoles || []).map((r: any) => r.user_id).filter(Boolean))
    );

    const { data: staffProfiles } = staffUserIds.length
      ? await supabase.from("profiles").select("user_id, full_name, email").in("user_id", staffUserIds)
      : { data: [] as any[] };

    // ARC committee members for this association
    let committee: { name: string | null; email: string | null }[] = [];
    if (args.associationId) {
      const { data: cm } = await supabase
        .from("arc_committee_members")
        .select("name, email")
        .eq("association_id", args.associationId)
        .eq("is_active", true);
      committee = (cm || []).filter((m: any) => m?.email);
    }

    // In-app notifications for ARC committee members who have user accounts (matched by email)
    try {
      const committeeEmails = committee.map((m) => (m.email || "").toLowerCase()).filter(Boolean);
      if (committeeEmails.length) {
        const { data: matchedProfiles } = await supabase
          .from("profiles")
          .select("user_id, email")
          .in("email", committeeEmails);
        const link = "https://avria.cloud/arc";
        for (const p of matchedProfiles || []) {
          await supabase.from("in_app_notifications").insert({
            user_id: p.user_id,
            type: "arc_application_submitted",
            title: "New ARC application to review",
            message: `${args.applicationTitle}${args.associationName ? " — " + args.associationName : ""}`,
            related_item_id: args.applicationId,
            related_item_type: "arc_application",
            link: "/arc",
          });
        }
      }
    } catch (e) {
      console.error("ARC committee in-app notify failed", e);
    }

    const staffRecipients = (staffProfiles || []).filter((p: any) => p?.email).map((p: any) => ({
      email: p.email, name: p.full_name, userId: p.user_id, link: "https://avria.cloud/dashboard/arc-applications",
    }));
    const committeeRecipients = committee.map((m) => ({
      email: m.email!, name: m.name || undefined, userId: `committee-${(m.email || "").toLowerCase()}`,
      link: "https://avria.cloud/arc",
    }));
    const recipients = [...staffRecipients, ...committeeRecipients].filter(
      (r, idx, arr) => r.email && arr.findIndex((x) => (x.email || "").toLowerCase() === (r.email || "").toLowerCase()) === idx,
    );
    if (recipients.length === 0) return;
    const stamp = Date.now();

    await Promise.allSettled(
      recipients.map((p) =>
        supabase.functions.invoke("send-transactional-email", {
          body: {
            templateName: "arc-application-submitted",
            recipientEmail: p.email,
            idempotencyKey: `arc-submitted-${args.applicationId}-${p.userId}-${stamp}`,
            templateData: {
              recipientName: p.name || undefined,
              homeownerName: args.homeownerName,
              associationName: args.associationName,
              propertyAddress: args.propertyAddress,
              applicationTitle: args.applicationTitle,
              projectType: args.projectType || undefined,
              description: args.description || undefined,
              fileCount: args.fileCount,
              link: p.link,
            },
          },
        })
      )
    );
  } catch (err) {
    console.error("notifyStaffOfArcSubmission failed", err);
  }
}
