import { NextRequest, NextResponse } from "next/server"; import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; interface Task { id: string; headline: string; projectName: string; projectId: number; status: number; dueDate: string | null; milestone: string | null; details: string | null; } async function getLeantimeUserId(email: string): Promise { try { const response = await fetch(`${process.env.LEANTIME_API_URL}/api/jsonrpc`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${process.env.LEANTIME_TOKEN}`, }, body: JSON.stringify({ jsonrpc: '2.0', method: 'leantime.rpc.users.getAll', id: 1, }), }); if (!response.ok) { console.error('Failed to fetch Leantime users'); return null; } const data = await response.json(); const users = data.result; const user = users.find((u: any) => u.email === email); return user ? user.id : null; } catch (error) { console.error('Error fetching Leantime user ID:', error); return null; } } export async function GET(request: NextRequest) { try { const session = await getServerSession(authOptions); if (!session?.user?.email) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const userId = await getLeantimeUserId(session.user.email); if (!userId) { return NextResponse.json({ error: "User not found in Leantime" }, { status: 404 }); } // Fetch tasks assigned to the user const response = await fetch(`${process.env.LEANTIME_API_URL}/api/jsonrpc`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${process.env.LEANTIME_TOKEN}`, }, body: JSON.stringify({ jsonrpc: '2.0', method: 'leantime.rpc.tickets.getAll', params: { userId: userId, status: "all", }, id: 1, }), }); if (!response.ok) { throw new Error('Failed to fetch tasks from Leantime'); } const data = await response.json(); const tasks = data.result.map((task: any) => ({ id: task.id.toString(), headline: task.headline, projectName: task.projectName, projectId: task.projectId, status: task.status, dueDate: task.dateToFinish || null, milestone: task.milestoneName || null, details: task.description || null, })); return NextResponse.json({ tasks }); } catch (error) { console.error('Error in tasks route:', error); return NextResponse.json( { error: "Failed to fetch tasks" }, { status: 500 } ); } }