import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { requireApiAdmin } from "@/lib/apiAuth";

function summarize(description: string) {
  if (description.length <= 100) return description;
  return `${description.slice(0, 100)}...`;
}

function parseNewsTime(value: unknown) {
  if (typeof value !== "string" && typeof value !== "number") return null;
  const date = new Date(value);
  return Number.isNaN(date.getTime()) ? null : date;
}

export async function GET(req: NextRequest) {
  const mode = req.headers.get("x-news-mode")?.toLowerCase();
  const summaryHeader = req.headers.get("x-news-summary")?.toLowerCase();
  const latestSummary = mode === "latest" || summaryHeader === "true";

  const news = await db.fantasyNews.findMany({
    orderBy: [{ newsTime: "desc" }, { createdAt: "desc" }],
    take: latestSummary ? 4 : undefined,
  });

  return NextResponse.json({
    data: news.map((item) => ({
      id: item.id,
      icon: item.icon,
      title: item.title,
      description: latestSummary ? summarize(item.description) : item.description,
      newsTime: item.newsTime.toISOString(),
      createdAt: item.createdAt.toISOString(),
      updatedAt: item.updatedAt.toISOString(),
    })),
  });
}

export async function POST(req: NextRequest) {
  const admin = await requireApiAdmin(req);
  if (!admin) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { icon, title, description, newsTime } = await req.json().catch(() => ({}));
  const parsedNewsTime = parseNewsTime(newsTime);

  if (
    typeof icon !== "string" ||
    !icon.trim() ||
    typeof title !== "string" ||
    !title.trim() ||
    typeof description !== "string" ||
    !description.trim() ||
    !parsedNewsTime
  ) {
    return NextResponse.json(
      { error: "icon، title، description و newsTime معتبر الزامی هستند" },
      { status: 400 },
    );
  }

  const item = await db.fantasyNews.create({
    data: {
      icon: icon.trim(),
      title: title.trim(),
      description: description.trim(),
      newsTime: parsedNewsTime,
    },
  });

  return NextResponse.json(
    {
      id: item.id,
      icon: item.icon,
      title: item.title,
      description: item.description,
      newsTime: item.newsTime.toISOString(),
      createdAt: item.createdAt.toISOString(),
    },
    { status: 201 },
  );
}
