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

const MASKED = "••••••••";

export async function POST(request: NextRequest) {
  try {
    await requireApiAuth();
    const body = await request.json().catch(() => ({}));

    const host = String(body.host || "");
    const port = parseInt(String(body.port)) || 993;
    const user = String(body.user || "");
    let pass = String(body.pass || "");
    const tls = body.tls !== false;

    if (!pass || pass === MASKED) {
      const settings = await prisma.appSettings.findUnique({ where: { id: "singleton" } });
      pass = settings?.emailImapPass || "";
    }

    if (!host || !user || !pass) {
      return NextResponse.json(
        { error: "Host, username, and password are required" },
        { status: 400 }
      );
    }

    const result = await testEmailConnection({ host, port, user, pass, tls, folder: "INBOX" });

    if (result.ok) {
      return NextResponse.json({
        ok: true,
        folders: result.folders,
        message: `Connected to ${host} — ${result.folders?.length || 0} folder(s) found`,
      });
    } else {
      return NextResponse.json(
        { ok: false, error: result.error },
        { status: 400 }
      );
    }
  } catch (error) {
    return handleApiError(error);
  }
}
