2026-04-07 12:41:52 -04:00
|
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
|
|
|
import { prisma } from "@/lib/db";
|
2026-04-16 00:51:44 -04:00
|
|
|
import { scanInbox } from "@/lib/email-watcher";
|
2026-04-07 12:41:52 -04:00
|
|
|
|
|
|
|
|
export async function POST(request: NextRequest) {
|
|
|
|
|
try {
|
|
|
|
|
const body = await request.json().catch(() => ({}));
|
|
|
|
|
const action = body.action as string | undefined;
|
|
|
|
|
|
2026-04-16 00:51:44 -04:00
|
|
|
if (!action || !["enable", "disable", "scan"].includes(action)) {
|
2026-04-07 12:41:52 -04:00
|
|
|
return NextResponse.json(
|
2026-04-16 00:51:44 -04:00
|
|
|
{ error: "Invalid action. Use 'enable', 'disable', 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-16 00:51:44 -04:00
|
|
|
const settings = await prisma.appSettings.findUnique({
|
|
|
|
|
where: { id: "singleton" },
|
|
|
|
|
});
|
2026-04-07 12:41:52 -04:00
|
|
|
|
2026-04-16 00:51:44 -04:00
|
|
|
if (!settings) {
|
|
|
|
|
return NextResponse.json(
|
|
|
|
|
{ error: "Settings not configured" },
|
|
|
|
|
{ status: 400 }
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-04-07 12:41:52 -04:00
|
|
|
|
2026-04-16 00:51:44 -04:00
|
|
|
if (action === "enable") {
|
2026-04-07 12:41:52 -04:00
|
|
|
if (!settings.emailImapHost || !settings.emailImapUser || !settings.emailImapPass) {
|
|
|
|
|
return NextResponse.json(
|
|
|
|
|
{ error: "IMAP host, username, and password are required" },
|
|
|
|
|
{ status: 400 }
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-16 00:51:44 -04:00
|
|
|
await prisma.appSettings.update({
|
|
|
|
|
where: { id: "singleton" },
|
|
|
|
|
data: { emailWatching: true },
|
2026-04-07 12:41:52 -04:00
|
|
|
});
|
|
|
|
|
} else {
|
2026-04-16 00:51:44 -04:00
|
|
|
await prisma.appSettings.update({
|
|
|
|
|
where: { id: "singleton" },
|
|
|
|
|
data: { emailWatching: false },
|
|
|
|
|
});
|
2026-04-07 12:41:52 -04:00
|
|
|
}
|
|
|
|
|
|
2026-04-16 00:51:44 -04:00
|
|
|
const updated = await prisma.appSettings.findUnique({ where: { id: "singleton" } });
|
|
|
|
|
return NextResponse.json({ emailWatching: updated?.emailWatching ?? false });
|
2026-04-07 12:41:52 -04:00
|
|
|
} 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 });
|
|
|
|
|
}
|
|
|
|
|
}
|