import { NextRequest, NextResponse } from "next/server";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";

export async function GET(
  request: NextRequest,
  { params }: { params: { orgId: string } }
) {
  try {
    const supabase = createRouteHandlerClient({ cookies });

    // 1) Authentification
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // 2) Vérifier que l'utilisateur est staff
    const { data: me } = await supabase
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .maybeSingle();

    if (!me?.is_staff) {
      return NextResponse.json({ error: "Forbidden: staff only" }, { status: 403 });
    }

    // 3) Récupérer les détails de l'organisation
    const { data: orgDetails, error } = await supabase
      .from("organization_details")
      .select("email_notifs, email_notifs_cc")
      .eq("org_id", params.orgId)
      .maybeSingle();

    if (error) {
      console.error("[get-org-emails] Error:", error);
      return NextResponse.json(
        { error: "Failed to fetch organization details", details: error.message },
        { status: 500 }
      );
    }

    if (!orgDetails) {
      return NextResponse.json(
        { 
          email_notifs: null,
          email_notifs_cc: null,
          message: "No organization details found"
        },
        { status: 200 }
      );
    }

    return NextResponse.json({
      email_notifs: orgDetails.email_notifs,
      email_notifs_cc: orgDetails.email_notifs_cc
    });

  } catch (err: any) {
    console.error("[get-org-emails] Error:", err);
    return NextResponse.json(
      { error: err.message || "Internal server error" },
      { status: 500 }
    );
  }
}
