import { NextRequest, NextResponse } from "next/server"; import { getServerSession } from "next-auth/next"; import { authOptions } from "@/app/api/auth/options"; import { prisma } from "@/lib/prisma"; import { discoverMicrosoftCalendars } from "@/lib/services/microsoft-calendar-sync"; import { logger } from "@/lib/logger"; /** * Discover calendars for a Microsoft account * POST /api/calendars/sync/discover-microsoft */ export async function POST(req: NextRequest) { try { const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json({ error: "Non authentifié" }, { status: 401 }); } const { mailCredentialId } = await req.json(); if (!mailCredentialId) { return NextResponse.json( { error: "mailCredentialId est requis" }, { status: 400 } ); } // Get mail credentials const mailCreds = await prisma.mailCredentials.findFirst({ where: { id: mailCredentialId, userId: session.user.id, }, }); if (!mailCreds) { return NextResponse.json( { error: "Credentials non trouvés" }, { status: 404 } ); } // Check if it's a Microsoft account if (!mailCreds.host.includes('outlook.office365.com') || !mailCreds.use_oauth) { return NextResponse.json( { error: "Ce compte n'est pas un compte Microsoft OAuth" }, { status: 400 } ); } if (!mailCreds.refresh_token) { return NextResponse.json( { error: "Refresh token requis pour la synchronisation Microsoft" }, { status: 400 } ); } // Discover calendars const calendars = await discoverMicrosoftCalendars( session.user.id, mailCreds.email ); logger.info('Microsoft calendars discovered', { userId: session.user.id, email: mailCreds.email, calendarsCount: calendars.length, }); return NextResponse.json({ calendars }); } catch (error) { logger.error('Error discovering Microsoft calendars', { error: error instanceof Error ? error.message : String(error), }); return NextResponse.json( { error: "Erreur lors de la découverte des calendriers", details: error instanceof Error ? error.message : String(error), }, { status: 500 } ); } }