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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const threadId = searchParams.get("threadId");

    if (!threadId) {
      return NextResponse.json(
        { error: "threadId query parameter is required" },
        { status: 400 }
      );
    }

    // Verify thread exists
    const thread = await prisma.forumThread.findUnique({
      where: { id: threadId },
    });

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

    const posts = await prisma.forumPost.findMany({
      where: { threadId },
      include: {
        author: {
          select: { id: true, name: true, isPremium: true, isPro: true },
        },
      },
      orderBy: { createdAt: "asc" },
    });

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

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 posting. Upgrade to Premium or Pro to participate in discussions." },
        { status: 403 }
      );
    }

    const { content, threadId } = await request.json();

    if (!content || !threadId) {
      return NextResponse.json(
        { error: "Missing required fields: content, threadId" },
        { status: 400 }
      );
    }

    // Verify thread exists
    const thread = await prisma.forumThread.findUnique({
      where: { id: threadId },
    });

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

    const post = await prisma.forumPost.create({
      data: {
        content,
        threadId,
        authorId: user.id,
        shariahStatus: "pending",
      },
      include: {
        author: {
          select: { id: true, name: true, isPremium: true, isPro: true },
        },
      },
    });

    // ── Auto-moderation for post content ──────────────────────────────
    const result = moderateContent(content);
    if (result.status === "approved") {
      await prisma.forumPost.update({
        where: { id: post.id },
        data: { shariahStatus: "approved" },
      });
      post.shariahStatus = "approved";
    } else {
      await prisma.forumPost.update({
        where: { id: post.id },
        data: { shariahFlags: JSON.stringify(result.flags) },
      });
      post.shariahFlags = JSON.stringify(result.flags);
    }

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