import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/db"; import { startEmailWatching, stopEmailWatching, isEmailWatching, scanInbox, } 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", "scan"].includes(action)) { return NextResponse.json( { error: "Invalid action. Use 'start', 'stop', or 'scan'" }, { status: 400 } ); } if (action === "scan") { const result = await scanInbox(); if (result.error) { return NextResponse.json({ error: result.error, ...result }, { status: 500 }); } return NextResponse.json({ ok: true, ...result }); } 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 }); } }