import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { sharePointScannerService } from "@/lib/services/sharePointScannerService";

async function authenticated() {
  const session = await getServerSession(authOptions);
  if (!session?.user) throw new Error("No autenticado");
  return session;
}

export async function GET() {
  try {
    const session = await authenticated();
    // Un administrador puede supervisar y operar todas las sesiones activas.
    const activeSessions = await sharePointScannerService.activeSessions(session.user.id, session.user.role);
    const activeSession = activeSessions.find((item) => item.userId === session.user.id) ?? null;
    const busyFolderPaths = await sharePointScannerService.activeFolderPaths();
    return NextResponse.json({ success: true, enabled: sharePointScannerService.isEnabled(), afterDownload: sharePointScannerService.afterDownloadAction(), folders: sharePointScannerService.folders(), busyFolderPaths, activeSession, activeSessions });
  } catch (error) {
    return NextResponse.json({ error: error instanceof Error ? error.message : "Error al consultar SharePoint" }, { status: 401 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const session = await authenticated();
    const body = await request.json() as { folderPath?: string; categoryId?: string; customFields?: string; confirmClear?: boolean };
    if (!body.folderPath || !body.categoryId || !body.customFields?.trim()) {
      return NextResponse.json({ error: "Carpeta, categoría y campos de extracción son obligatorios." }, { status: 400 });
    }
    const result = await sharePointScannerService.createSession({
      userId: session.user.id,
      categoryId: body.categoryId,
      folderPath: body.folderPath,
      customFields: body.customFields,
      confirmClear: body.confirmClear === true,
    });
    if (result.confirmationRequired) {
      return NextResponse.json({ success: false, confirmationRequired: true, pendingFiles: result.pending.map((file) => ({ id: file.id, name: file.name })) }, { status: 409 });
    }
    return NextResponse.json({ success: true, session: result.session, clearedFiles: result.deleted }, { status: 201 });
  } catch (error) {
    return NextResponse.json({ error: error instanceof Error ? error.message : "No se pudo iniciar la sesión." }, { status: 500 });
  }
}
