import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; import { fetchMatchesAndTeamsFifa, fetchFifaScores, applyFifaScores, attachFifaGoals } from "@/lib/feeds"; import type { Match, Team } from "@/lib/types"; export const dynamic = "force-dynamic"; const RECENT_MS = 60 * 60 * 1000; const MATCH_DURATION = 2.5 * 60 * 60 * 1000; function isRecentlyFinished(m: Match): boolean { if (m.status !== "FINISHED") return false; const kickoff = new Date(m.utcDate).getTime(); if (isNaN(kickoff)) return false; return kickoff + MATCH_DURATION > Date.now() - RECENT_MS; } export async function GET(request: NextRequest) { const locale = request.nextUrl.searchParams.get("locale") || "de"; try { const { matches: rawMatches, teams } = await fetchMatchesAndTeamsFifa(locale); const relevant = rawMatches.filter(m => m.status === "LIVE" || m.status === "IN_PLAY" || m.status === "PAUSED" || isRecentlyFinished(m), ); if (relevant.length === 0) { return NextResponse.json({ updatedAt: new Date().toISOString(), liveCount: 0, recentCount: 0, teams: [] as Team[], matches: [] as Match[], }); } let fifaData: Awaited>; try { fifaData = await fetchFifaScores(); } catch { return NextResponse.json({ updatedAt: new Date().toISOString(), liveCount: relevant.filter(m => m.status !== "FINISHED").length, recentCount: relevant.filter(m => m.status === "FINISHED").length, teams, matches: relevant, goalsFailed: true, }); } let matches = applyFifaScores(relevant, teams, fifaData); let goalsFailed = false; try { matches = await attachFifaGoals(matches, fifaData, locale); } catch { goalsFailed = true; } const liveCount = matches.filter(m => m.status === "LIVE" || m.status === "IN_PLAY" || m.status === "PAUSED").length; const recentCount = matches.filter(m => m.status === "FINISHED" && isRecentlyFinished(m)).length; return NextResponse.json({ updatedAt: new Date().toISOString(), liveCount, recentCount, teams, matches, goalsFailed, }); } catch (err) { const message = err instanceof Error ? err.message : "unbekannter Fehler"; return NextResponse.json( { error: "Live-Feed nicht erreichbar", detail: message }, { status: 502 }, ); } }