2026-04-07 12:41:52 -04:00
|
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
|
|
|
import { prisma } from "@/lib/db";
|
|
|
|
|
import {
|
|
|
|
|
startEmailWatching,
|
|
|
|
|
stopEmailWatching,
|
|
|
|
|
isEmailWatching,
|
2026-04-10 14:04:45 -04:00
|
|
|
scanInbox,
|
2026-04-07 12:41:52 -04:00
|
|
|
} from "@/lib/email-watcher";
|
|
|
|
|
|
|
|
|
|
export async function POST(request: NextRequest) {
|
|
|
|
|
try {
|
|
|
|
|
const body = await request.json().catch(() => ({}));
|
|
|
|
|
const action = body.action as string | undefined;
|
|
|
|
|
|
2026-04-10 14:04:45 -04:00
|
|
|
if (!action || !["start", "stop", "scan"].includes(action)) {
|
2026-04-07 12:41:52 -04:00
|
|
|
return NextResponse.json(
|
2026-04-10 14:04:45 -04:00
|
|
|
{ error: "Invalid action. Use 'start', 'stop', or 'scan'" },
|
2026-04-07 12:41:52 -04:00
|
|
|
{ status: 400 }
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-10 14:04:45 -04:00
|
|
|
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 });
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-07 12:41:52 -04:00
|
|
|
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 });
|
|
|
|
|
}
|
|
|
|
|
}
|