import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAuth } from "@/lib/auth";
import { getUserTier, FORUM_LIMITS } from "@/lib/tiers";
import crypto from "crypto";

function generateInviteCode(): string {
  return crypto.randomBytes(4).toString("hex").slice(0, 8);
}

// POST /api/groups — create a group (premium only)
export async function POST(request: NextRequest) {
  try {
    const auth = await requireAuth(request);
    if (!auth) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const user = await prisma.user.findUnique({ where: { id: auth.userId } });
    if (!user) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    const tier = getUserTier(user.isPremium, user.isPro);
    const limits = FORUM_LIMITS[tier];

    if (!limits.canPost) {
      return NextResponse.json(
        { error: "Your tier does not support creating groups. Upgrade to Premium or Pro to create groups." },
        { status: 403 }
      );
    }

    const { name, description } = await request.json();

    if (!name || typeof name !== "string" || name.trim().length === 0) {
      return NextResponse.json(
        { error: "Missing required field: name" },
        { status: 400 }
      );
    }

    const inviteCode = generateInviteCode();

    const group = await prisma.group.create({
      data: {
        name: name.trim(),
        description: description?.trim() || null,
        ownerId: user.id,
        inviteCode,
        members: {
          create: {
            userId: user.id,
            role: "owner",
          },
        },
      },
      include: {
        owner: {
          select: { id: true, name: true, isPremium: true, isPro: true },
        },
        members: {
          include: {
            user: {
              select: { id: true, name: true, isPremium: true, isPro: true },
            },
          },
        },
        _count: {
          select: { members: true, threads: true },
        },
      },
    });

    return NextResponse.json({ group }, { status: 201 });
  } catch (error) {
    console.error("POST /api/groups error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

// GET /api/groups — list groups where current user is a member
export async function GET(request: NextRequest) {
  try {
    const auth = await requireAuth(request);
    if (!auth) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const groups = await prisma.group.findMany({
      where: {
        members: {
          some: {
            userId: auth.userId,
          },
        },
      },
      include: {
        owner: {
          select: { id: true, name: true, isPremium: true, isPro: true },
        },
        _count: {
          select: { members: true, threads: true },
        },
      },
      orderBy: { createdAt: "desc" },
    });

    return NextResponse.json({ groups });
  } catch (error) {
    console.error("GET /api/groups error:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
