import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireApiAuthWithPermission, handleApiError } from "@/lib/api-auth";

const VALID_ROLES = ["viewer", "reviewer", "editor", "admin"];

export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await requireApiAuthWithPermission("users.invite");
    const { id } = await params;
    const { role } = await req.json();

    if (!role || !VALID_ROLES.includes(role)) {
      return NextResponse.json(
        { error: `Role must be one of: ${VALID_ROLES.join(", ")}` },
        { status: 400 }
      );
    }

    const target = await prisma.orgMember.findFirst({
      where: { id, organizationId: session.user.orgId },
    });

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

    if (target.role === "owner") {
      return NextResponse.json(
        { error: "Cannot change the owner's role" },
        { status: 403 }
      );
    }

    if (target.userId === session.user.id) {
      return NextResponse.json(
        { error: "You cannot change your own role" },
        { status: 403 }
      );
    }

    const updated = await prisma.orgMember.update({
      where: { id },
      data: { role },
      include: { user: { select: { id: true, email: true, displayName: true } } },
    });

    return NextResponse.json({ member: updated });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await requireApiAuthWithPermission("users.invite");
    const { id } = await params;

    const target = await prisma.orgMember.findFirst({
      where: { id, organizationId: session.user.orgId },
    });

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

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

    if (target.userId === session.user.id) {
      return NextResponse.json(
        { error: "You cannot remove yourself" },
        { status: 403 }
      );
    }

    await prisma.$transaction([
      prisma.orgMember.delete({ where: { id } }),
      prisma.user.updateMany({
        where: { id: target.userId, activeOrgId: session.user.orgId },
        data: { activeOrgId: null },
      }),
    ]);

    return NextResponse.json({ success: true });
  } catch (error) {
    return handleApiError(error);
  }
}
