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

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

  try {
    const { email, role = "developer" } = (await request.json()) as {
      email: string;
      role?: string;
    };

    if (!email?.trim()) {
      return NextResponse.json({ error: "Email is required" }, { status: 400 });
    }

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

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

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

    if (user.teamRole !== "admin") {
      return NextResponse.json({ error: "Only admins can invite members" }, { status: 403 });
    }

    // Check team seat limits
    const team = await db.team.findUnique({
      where: { id: user.teamId },
      select: { id: true, maxSeats: true, _count: { select: { members: true } } },
    });

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

    if (team._count.members >= team.maxSeats) {
      return NextResponse.json(
        { error: `Team is at capacity (${team.maxSeats} seats)` },
        { status: 409 },
      );
    }

    // Check if user is already a member
    const existingMember = await db.user.findFirst({
      where: { email: email.trim().toLowerCase(), teamId: user.teamId },
    });

    if (existingMember) {
      return NextResponse.json({ error: "User is already a team member" }, { status: 409 });
    }

    // Check for existing pending invite
    const existingInvite = await db.teamInvite.findFirst({
      where: { teamId: user.teamId, email: email.trim().toLowerCase(), acceptedAt: null },
    });

    if (existingInvite) {
      return NextResponse.json({ error: "Invite already pending for this email" }, { status: 409 });
    }

    const token = randomBytes(32).toString("base64url");
    const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days

    const invite = await db.teamInvite.create({
      data: {
        teamId: user.teamId,
        email: email.trim().toLowerCase(),
        role,
        token,
        invitedById: session.user.id,
        expiresAt,
      },
    });

    // TODO: Send invite email via sendTeamInviteEmail when available

    logger.info(
      { action: "team_invite", teamId: user.teamId, inviteId: invite.id },
      "Team invite created",
    );

    return NextResponse.json({ invite: { id: invite.id, email: invite.email, role: invite.role, expiresAt } }, { status: 201 });
  } catch (error) {
    logger.error({ err: error, action: "team_invite" }, "Failed to create invite");
    return NextResponse.json({ error: "Failed to create invite" }, { status: 500 });
  }
}

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

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

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

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

    await db.teamInvite.delete({
      where: { id: inviteId, teamId: user.teamId },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    logger.error({ err: error, action: "team_invite_revoke" }, "Failed to revoke invite");
    return NextResponse.json({ error: "Failed to revoke invite" }, { status: 500 });
  }
}
