import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";

/** PATCH /api/team/members — update a member's role */
export async function PATCH(request: Request) {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const { memberId, role } = (await request.json()) as {
      memberId: string;
      role: string;
    };

    const validRoles = ["admin", "developer", "viewer"];
    if (!validRoles.includes(role)) {
      return NextResponse.json({ error: "Invalid role" }, { status: 400 });
    }

    const currentUser = await db.user.findUnique({
      where: { id: session.user.id },
      select: { teamId: true, teamRole: true },
    });

    if (!currentUser?.teamId || currentUser.teamRole !== "admin") {
      return NextResponse.json({ error: "Only admins can update roles" }, { status: 403 });
    }

    // Prevent removing the last admin
    if (memberId === session.user.id && role !== "admin") {
      const adminCount = await db.user.count({
        where: { teamId: currentUser.teamId, teamRole: "admin" },
      });
      if (adminCount <= 1) {
        return NextResponse.json(
          { error: "Cannot remove the last admin" },
          { status: 409 },
        );
      }
    }

    const member = await db.user.findFirst({
      where: { id: memberId, teamId: currentUser.teamId },
    });

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

    await db.user.update({
      where: { id: memberId },
      data: { teamRole: role },
    });

    logger.info(
      { action: "team_member_role_update", teamId: currentUser.teamId, memberId, role },
      "Team member role updated",
    );

    return NextResponse.json({ success: true, memberId, role });
  } catch (error) {
    logger.error({ err: error, action: "team_member_update" }, "Failed to update member");
    return NextResponse.json({ error: "Failed to update member" }, { status: 500 });
  }
}

/** DELETE /api/team/members — remove a member from the team */
export async function DELETE(request: Request) {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const { memberId } = (await request.json()) as { memberId: string };

    const currentUser = await db.user.findUnique({
      where: { id: session.user.id },
      select: { teamId: true, teamRole: true },
    });

    if (!currentUser?.teamId) {
      return NextResponse.json({ error: "You are not in a team" }, { status: 403 });
    }

    // Admins can remove anyone, members can remove themselves
    const isSelf = memberId === session.user.id;
    if (!isSelf && currentUser.teamRole !== "admin") {
      return NextResponse.json({ error: "Only admins can remove members" }, { status: 403 });
    }

    const member = await db.user.findFirst({
      where: { id: memberId, teamId: currentUser.teamId },
    });

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

    // Check if removing the team owner
    const team = await db.team.findUnique({
      where: { id: currentUser.teamId },
      select: { ownerId: true },
    });

    if (team?.ownerId === memberId) {
      return NextResponse.json(
        { error: "Cannot remove the team owner. Transfer ownership first." },
        { status: 409 },
      );
    }

    await db.user.update({
      where: { id: memberId },
      data: { teamId: null, teamRole: null },
    });

    logger.info(
      { action: "team_member_remove", teamId: currentUser.teamId, memberId, self: isSelf },
      "Team member removed",
    );

    return NextResponse.json({ success: true });
  } catch (error) {
    logger.error({ err: error, action: "team_member_remove" }, "Failed to remove member");
    return NextResponse.json({ error: "Failed to remove member" }, { status: 500 });
  }
}
