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

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

    const { id, memberId } = await params;

    // Find the group and verify the requester is the owner
    const group = await prisma.group.findUnique({
      where: { id },
    });

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

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

    // Find the membership to remove
    const membership = await prisma.groupMember.findUnique({
      where: { id: memberId },
    });

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

    if (membership.groupId !== id) {
      return NextResponse.json(
        { error: "Member does not belong to this group" },
        { status: 400 }
      );
    }

    // Cannot remove the owner
    if (membership.role === "owner") {
      return NextResponse.json(
        { error: "Cannot remove the group owner" },
        { status: 403 }
      );
    }

    await prisma.groupMember.delete({
      where: { id: memberId },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("DELETE /api/groups/[id]/members/[memberId] error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
