import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { scanInbox } from "@/lib/email-watcher";
import { requireApiAuth, handleApiError } from "@/lib/api-auth";

export async function POST(request: NextRequest) {
  try {
    await requireApiAuth();
    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) {
    return handleApiError(error);
  }
}
