import { apiFootball } from "./context.js";
import { MatchSnapshot, TeamSnapshot } from "../types.js";
export const buildMatchSnapshot = async (matchId: number): Promise<MatchSnapshot> => {
const fixture = await apiFootball.getFixture(matchId);
if (!fixture) {
throw new Error(`Fixture ${matchId} not found on API-Football`);
}
const standings = await apiFootball.getStandingsMap();
const [homeStats, awayStats] = await Promise.all([
apiFootball.getTeamStatistics(fixture.homeTeam.id),
apiFootball.getTeamStatistics(fixture.awayTeam.id),
]);
const [homeResults, awayResults] = await Promise.all([
apiFootball.getRecentMatches(fixture.homeTeam.id),
apiFootball.getRecentMatches(fixture.awayTeam.id),
]);
const homeSnapshot = enrichTeamSnapshot(fixture.homeTeam.id, standings, homeStats, homeResults);
const awaySnapshot = enrichTeamSnapshot(fixture.awayTeam.id, standings, awayStats, awayResults);
return {
match: fixture,
home: {
...homeSnapshot,
team: fixture.homeTeam,
},
away: {
...awaySnapshot,
team: fixture.awayTeam,
},
};
};
const enrichTeamSnapshot = (
teamId: number,
standings: Map<number, { position: number; points: number; form?: string }>,
stats: { avgGoalsFor: number; avgGoalsAgainst: number } | undefined,
recentResults: TeamSnapshot["recentResults"],
): Omit<TeamSnapshot, "team"> => {
const standing = standings.get(teamId);
return {
leaguePosition: standing?.position,
points: standing?.points,
form: standing?.form,
avgGoalsFor: stats?.avgGoalsFor,
avgGoalsAgainst: stats?.avgGoalsAgainst,
recentResults,
};
};