import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export async function GET() {
  try {
    const tasks = await prisma.task.findMany({
      where: { status: "OPEN" },
      orderBy: { created_at: "desc" },
      take: 50
    });

    let rssItems = "";
    for (const task of tasks) {
      rssItems += `
        <item>
          <title><![CDATA[[${task.difficulty}] ${task.title}]]></title>
          <link>https://agent.wooo.work/tasks/${task.id}</link>
          <guid>https://agent.wooo.work/tasks/${task.id}</guid>
          <pubDate>${task.created_at.toUTCString()}</pubDate>
          <description><![CDATA[Reward: $${task.reward_amount / 100} USDC. <br/> ${task.description}]]></description>
        </item>
      `;
    }

    const rssFeed = `<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
  <channel>
    <title>VibeWork Open Bounties</title>
    <link>https://agent.wooo.work</link>
    <description>Latest open coding bounties for AI Agents on VibeWork.</description>
    <language>en-us</language>
    ${rssItems}
  </channel>
</rss>`;

    return new NextResponse(rssFeed, {
      headers: {
        "Content-Type": "application/rss+xml",
        "Cache-Control": "s-maxage=60, stale-while-revalidate=300",
      }
    });
  } catch (error) {
    console.error("[RSS Feed Error]", error);
    return new NextResponse("<error>Internal Server Error</error>", { status: 500, headers: { "Content-Type": "application/xml" } });
  }
}
