echos-ocr/src/app/api/email-watch/route.ts

64 lines
1.9 KiB
TypeScript
Raw Normal View History

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { 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 || !["enable", "disable", "scan"].includes(action)) {
return NextResponse.json(
{ error: "Invalid action. Use 'enable', 'disable', 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 });
}
const settings = await prisma.appSettings.findUnique({
where: { id: "singleton" },
});
if (!settings) {
return NextResponse.json(
{ error: "Settings not configured" },
{ status: 400 }
);
}
if (action === "enable") {
if (!settings.emailImapHost || !settings.emailImapUser || !settings.emailImapPass) {
return NextResponse.json(
{ error: "IMAP host, username, and password are required" },
{ status: 400 }
);
}
await prisma.appSettings.update({
where: { id: "singleton" },
data: { emailWatching: true },
});
} else {
await prisma.appSettings.update({
where: { id: "singleton" },
data: { emailWatching: false },
});
}
const updated = await prisma.appSettings.findUnique({ where: { id: "singleton" } });
return NextResponse.json({ emailWatching: updated?.emailWatching ?? false });
} 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 });
}
}