import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/db"; import { startEmailWatching, stopEmailWatching, isEmailWatching, } from "@/lib/email-watcher"; export async function POST(request: NextRequest) { try { const body = await request.json().catch(() => ({})); const action = body.action as string | undefined; if (!action || !["start", "stop"].includes(action)) { return NextResponse.json( { error: "Invalid action. Use 'start' or 'stop'" }, { status: 400 } ); } if (action === "start") { const settings = await prisma.appSettings.findUnique({ where: { id: "singleton" }, }); if (!settings) { return NextResponse.json( { error: "Settings not configured" }, { status: 400 } ); } if (!settings.emailImapHost || !settings.emailImapUser || !settings.emailImapPass) { return NextResponse.json( { error: "IMAP host, username, and password are required" }, { status: 400 } ); } await startEmailWatching({ host: settings.emailImapHost, port: settings.emailImapPort, user: settings.emailImapUser, pass: settings.emailImapPass, tls: settings.emailImapTls, folder: settings.emailFolder, processedAction: settings.emailProcessed, processedFolder: settings.emailProcessedFolder, }); } else { await stopEmailWatching(); } return NextResponse.json({ emailWatching: isEmailWatching() }); } catch (error) { console.error("[email-watch POST]", error); const message = error instanceof Error ? error.message : "Failed to update email watch"; return NextResponse.json({ error: message }, { status: 500 }); } }