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

/** POST /api/team/invite/accept — accept a team invite via token */
export async function POST(request: Request) {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

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

    if (!token) {
      return NextResponse.json({ error: "Invite token is required" }, { status: 400 });
    }

    const invite = await db.teamInvite.findUnique({
      where: { token },
      include: { team: { select: { id: true, name: true, maxSeats: true, _count: { select: { members: true } } } } },
    });

    if (!invite) {
      return NextResponse.json({ error: "Invalid invite token" }, { status: 404 });
    }

    if (invite.acceptedAt) {
      return NextResponse.json({ error: "Invite already accepted" }, { status: 409 });
    }

    if (invite.expiresAt < new Date()) {
      return NextResponse.json({ error: "Invite has expired" }, { status: 410 });
    }

    // Verify the accepting user matches the invite email
    const user = await db.user.findUnique({
      where: { id: session.user.id },
      select: { id: true, email: true, teamId: true },
    });

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

    if (user.email.toLowerCase() !== invite.email.toLowerCase()) {
      return NextResponse.json(
        { error: "This invite was sent to a different email address" },
        { status: 403 },
      );
    }

    if (user.teamId) {
      return NextResponse.json({ error: "You are already in a team" }, { status: 409 });
    }

    // Check seat limit
    if (invite.team._count.members >= invite.team.maxSeats) {
      return NextResponse.json({ error: "Team is at capacity" }, { status: 409 });
    }

    // Accept the invite: join team + mark invite as accepted
    await db.$transaction([
      db.user.update({
        where: { id: session.user.id },
        data: { teamId: invite.teamId, teamRole: invite.role },
      }),
      db.teamInvite.update({
        where: { id: invite.id },
        data: { acceptedAt: new Date() },
      }),
    ]);

    logger.info(
      { action: "team_invite_accept", teamId: invite.teamId, userId: session.user.id },
      "Team invite accepted",
    );

    return NextResponse.json({
      success: true,
      team: { id: invite.team.id, name: invite.team.name },
      role: invite.role,
    });
  } catch (error) {
    logger.error({ err: error, action: "team_invite_accept" }, "Failed to accept invite");
    return NextResponse.json({ error: "Failed to accept invite" }, { status: 500 });
  }
}
