import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { NextResponse } from "next/server"; export async function GET() { const session = await getServerSession(authOptions); if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } try { console.log('Fetching status labels for user:', session.user.id); console.log('Using LEANTIME_TOKEN:', process.env.LEANTIME_TOKEN ? 'Present' : 'Missing'); // First, get the Leantime user ID for the current user const userResponse = await fetch('https://agilite.slm-lab.net/api/jsonrpc', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': process.env.LEANTIME_TOKEN || '', }, body: JSON.stringify({ method: 'leantime.rpc.Users.Users.getUserByEmail', jsonrpc: '2.0', id: 1, params: { email: session.user.email } }) }); const userData = await userResponse.json(); console.log('User lookup response:', userData); if (!userData.result || !userData.result.id) { throw new Error('Could not find Leantime user ID'); } const leantimeUserId = userData.result.id; // Now fetch the status labels const response = await fetch('https://agilite.slm-lab.net/api/jsonrpc', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-Key': process.env.LEANTIME_TOKEN || '', }, body: JSON.stringify({ method: 'leantime.rpc.Tickets.Tickets.getAllStatusLabelsByUserId', jsonrpc: '2.0', id: 1, params: { userId: leantimeUserId } }) }); const responseText = await response.text(); console.log('Leantime API Response Status:', response.status); console.log('Leantime API Response Headers:', response.headers); console.log('Leantime API Response Body:', responseText); if (!response.ok) { if (response.status === 401) { return NextResponse.json({ error: "Unauthorized access to Leantime API" }, { status: 401 }); } if (response.status === 403) { return NextResponse.json({ error: "Forbidden access to Leantime API" }, { status: 403 }); } throw new Error(`Leantime API returned ${response.status}: ${responseText}`); } let data; try { data = JSON.parse(responseText); } catch (e) { console.error('Failed to parse Leantime response:', e); throw new Error('Invalid JSON response from Leantime'); } if (!data.result) { console.log('No result in Leantime response'); return NextResponse.json({ statusLabels: [] }); } return NextResponse.json({ statusLabels: data.result }); } catch (error) { console.error('Detailed error in status labels fetch:', error); return NextResponse.json( { error: "Failed to fetch status labels", details: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 } ); } }