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

// POST /api/groups/[id]/join — join by invite code
export async function POST(
  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 { inviteCode } = await request.json();

    if (!inviteCode || typeof inviteCode !== "string") {
      return NextResponse.json(
        { error: "Missing required field: inviteCode" },
        { status: 400 }
      );
    }

    // Find the group and verify invite code
    const group = await prisma.group.findUnique({
      where: { id },
      include: {
        members: {
          where: { userId: auth.userId },
        },
      },
    });

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

    if (group.inviteCode !== inviteCode) {
      return NextResponse.json(
        { error: "Invalid invite code" },
        { status: 403 }
      );
    }

    // Check if user is already a member
    if (group.members.length > 0) {
      return NextResponse.json(
        { error: "You are already a member of this group" },
        { status: 409 }
      );
    }

    // Add user as member
    const membership = await prisma.groupMember.create({
      data: {
        groupId: id,
        userId: auth.userId,
        role: "member",
      },
      include: {
        user: {
          select: { id: true, name: true, isPremium: true, isPro: true },
        },
        group: {
          select: { id: true, name: true },
        },
      },
    });

    return NextResponse.json({ membership }, { status: 201 });
  } catch (error) {
    console.error("POST /api/groups/[id]/join error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
