import { NextResponse } from 'next/server'; import { token } from '@/discord.json'; import db from '@/lib/mongoose'; import Scrims from '@/schemas/scrims'; type TournamentType = "CTS_SOLO" | "CTS_DUO" | "CTS_TRIO" | "CTS_SQUAD"; type TournamentDescription = string; const tournamentTypeMapping: Record = { CTS_SOLO: "NAC - Solos - Tournament Settings", CTS_DUO: "NAC - Duos - Tournament Settings", CTS_TRIO: "NAC - Trios - Tournament Settings", CTS_SQUAD: "NAC - Squads - Tournament Settings", }; export async function GET(request: Request, { params }: { params: { guildId: string, id: string } }) { try { console.log('API Route Hit'); await db.connect(); console.log('DB Connected'); const { guildId, id } = params; console.log('Extracted parameters:', { guildId, id }); if (!guildId || !id) { console.error('Error: Invalid guildId or tournament id'); return NextResponse.json({ error: 'Invalid guildId or tournament id' }, { status: 400 }); } const apiUrl = `https://yunite.xyz/api/v3/guild/${guildId}/tournaments/${id}`; const response = await fetch(apiUrl, { method: 'GET', headers: { 'Y-Api-Token': '823c33b2-fe58-4dac-9fe3-e2e05338824a', }, }); if (!response.ok) { const errorDetails = await response.text(); console.error(`Fetch error: ${response.status} - ${errorDetails}`); throw new Error(`Error fetching data: ${response.statusText}`); } const data = await response.json(); console.log('Fetched tournament data:', data); if (!data || !data.matchTemplate || data.matchTemplate.length === 0) { console.error('Error: Invalid data structure returned from the API.'); throw new Error('Invalid data structure returned from the API.'); } const matchTemplate = data.matchTemplate[0]; const signupChannel = matchTemplate.signUpChannelID; if (!signupChannel) { console.error('Error: No signup channel ID found in the fetched data.'); throw new Error('No signup channel ID found in the fetched data.'); } const startDate = new Date(data.startDate); const endDate = new Date(data.endDate); const gamemode = tournamentTypeMapping[matchTemplate.type as TournamentType] || matchTemplate.type; const queueSize = data.queueSize; const name = data.name; const gamemode1 = queueSize === 1 ? "Solo" : queueSize === 2 ? "Duo" : queueSize === 3 ? "Trio" : "Squad"; const newScrim = { guildId, totalScrims: [{ name, id, startDate, endDate, createdAt: new Date(), updatedAt: new Date(), }] }; console.log('Updating scrim data in the database...'); await Scrims.findOneAndUpdate( { guildId }, { $push: { totalScrims: newScrim.totalScrims[0] } }, { new: true, upsert: true } ); console.log('Scrim data updated successfully.'); const eventPayload = { name: `${name}`, scheduled_start_time: startDate.toISOString(), scheduled_end_time: endDate.toISOString(), entity_type: 3, privacy_level: 2, entity_metadata: { location: `<#${signupChannel}>` } }; const createEventUrl = `https://discord.com/api/v10/guilds/${guildId}/scheduled-events`; console.log('Creating event in Discord...'); const eventResponse = await fetch(createEventUrl, { method: 'POST', headers: { 'Authorization': `Bot ${token}`, 'Content-Type': 'application/json', }, body: JSON.stringify(eventPayload), }); if (!eventResponse.ok) { const eventErrorDetails = await eventResponse.text(); console.error(`Error creating event: ${eventResponse.statusText}, Details: ${eventErrorDetails}`); throw new Error(`Error creating event: ${eventResponse.statusText}`); } const eventData = await eventResponse.json(); const eventLink = `https://discord.com/events/${guildId}/${eventData.id}`; console.log('Event created successfully:', eventData); const announcementMsg = `**Excel Scrims** will be hosting **${gamemode1}s** __tomorrow__ at ****! <:IconTrophy:1255002838581641266>\n\n**Information:**\n> • ${gamemode}.\n> • <:MFLeaderboard:1232133052130529280> All Players get **EPR**.\n> • Codes Posted in <#${signupChannel}>.\n\nCheck out our **__Patreon Page__**! Tons of **INSANE** perks such as → (***Scrim Priority** **|** Gif, Pic and Nick Perms **|** **Self Promo***)\n> || ${eventLink} @everyone`; console.log('Sending announcement message to Discord...'); const messageResponse = await fetch(`https://discord.com/api/v10/channels/${signupChannel}/messages`, { method: 'POST', headers: { 'Authorization': `Bot ${token}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ content: announcementMsg }), }); if (!messageResponse.ok) { const messageErrorDetails = await messageResponse.text(); console.error(`Error sending message: ${messageResponse.statusText}, Details: ${messageErrorDetails}`); throw new Error(`Error sending message: ${messageResponse.statusText}`); } console.log('Message sent successfully'); return NextResponse.json({ data }, { status: 200 }); } catch (error) { console.log(error); return NextResponse.json({ error: 'Failed to fetch data' }, { status: 500 }); } }