/**
 * GET /api/team?brandId=xxx
 * Returns all org members for the brand's organization.
 * These are the valid assignees for tasks under this brand.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    select: { orgId: true },
  });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });

  const memberships = await prisma.orgMembership.findMany({
    where: { orgId: brand.orgId },
    include: {
      user: { select: { id: true, name: true, email: true, image: true } },
    },
    orderBy: { createdAt: "asc" },
  });

  const members = memberships.map((m) => ({
    id: m.user.id,
    name: m.user.name || m.user.email.split("@")[0],
    email: m.user.email,
    image: m.user.image,
    role: m.role,
  }));

  return NextResponse.json(members);
}
