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

/** GET /api/team — get current user's team (or null) */
export async function GET() {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

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

    if (!user?.teamId) {
      return NextResponse.json({ team: null });
    }

    const team = await db.team.findUnique({
      where: { id: user.teamId },
      include: {
        owner: { select: { id: true, name: true, email: true } },
        members: {
          select: {
            id: true,
            name: true,
            email: true,
            teamRole: true,
            createdAt: true,
          },
          orderBy: { createdAt: "asc" },
        },
        invites: {
          where: { acceptedAt: null },
          select: {
            id: true,
            email: true,
            role: true,
            createdAt: true,
            expiresAt: true,
          },
          orderBy: { createdAt: "desc" },
        },
      },
    });

    return NextResponse.json({ team, userRole: user.teamRole });
  } catch (error) {
    logger.error({ err: error, action: "team_get" }, "Failed to fetch team");
    return NextResponse.json({ error: "Failed to fetch team" }, { status: 500 });
  }
}

/** POST /api/team — create a new team (user must be on team or enterprise plan) */
export async function POST(request: Request) {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

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

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

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

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

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

    if (user.plan !== "team" && user.plan !== "enterprise") {
      return NextResponse.json(
        { error: "Team plan required. Upgrade to Team or Enterprise to create a team." },
        { status: 403 },
      );
    }

    const team = await db.team.create({
      data: {
        name: name.trim(),
        ownerId: session.user.id,
        members: { connect: { id: session.user.id } },
      },
    });

    await db.user.update({
      where: { id: session.user.id },
      data: { teamRole: "admin" },
    });

    logger.info({ action: "team_create", teamId: team.id, userId: session.user.id }, "Team created");
    return NextResponse.json({ team }, { status: 201 });
  } catch (error) {
    logger.error({ err: error, action: "team_create" }, "Failed to create team");
    return NextResponse.json({ error: "Failed to create team" }, { status: 500 });
  }
}
