import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAuth } from "@/lib/auth";

// GET /api/groups/[id]/invite — get invite code (owner only)
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const auth = await requireAuth(request);
    if (!auth) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = await params;

    const group = await prisma.group.findUnique({
      where: { id },
      select: {
        id: true,
        name: true,
        ownerId: true,
        inviteCode: true,
      },
    });

    if (!group) {
      return NextResponse.json({ error: "Group not found" }, { status: 404 });
    }

    // Only the owner can view the invite code
    if (group.ownerId !== auth.userId) {
      return NextResponse.json(
        { error: "Only the group owner can view the invite code" },
        { status: 403 }
      );
    }

    return NextResponse.json({
      groupId: group.id,
      inviteCode: group.inviteCode,
    });
  } catch (error) {
    console.error("GET /api/groups/[id]/invite error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
