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

const MODULE = '[GET /api/documents]';

/**
 * GET /api/documents
 * Obtener documentos del usuario autenticado
 */
export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || !session.user) {
      logger.warn(MODULE, 'Intento de acceso sin autenticación');
      return NextResponse.json({ error: "No autenticado" }, { status: 401 });
    }

    const query = request.nextUrl.searchParams.get("q") || undefined;
    const categoryId = request.nextUrl.searchParams.get("categoryId") || undefined;

    logger.info(MODULE, 'Obteniendo documentos', {
      userId: session.user.id,
      role: session.user.role,
      query,
      categoryId,
    });

    const documents = await documentService.getDocuments({
      query,
      categoryId,
      userId: session.user.id,
      role: session.user.role,
    });

    logger.info(MODULE, `Documentos encontrados: ${documents.length}`);

    return NextResponse.json({ success: true, documents });
  } catch (error) {
    logger.error(
      MODULE,
      'Error al obtener documentos',
      error instanceof Error ? error : undefined
    );
    return NextResponse.json(
      { error: "Error al obtener documentos" },
      { status: 500 }
    );
  }
}

/**
 * POST /api/documents
 * Crear un nuevo documento
 */
export async function POST(request: NextRequest) {
  const MODULE_POST = '[POST /api/documents]';
  let body: unknown;
  
  try {
    const session = await getServerSession(authOptions);

    if (!session || !session.user) {
      logger.warn(MODULE_POST, 'Intento de creación sin autenticación');
      return NextResponse.json({ error: "No autenticado" }, { status: 401 });
    }

    body = await request.json();
    const { fileName, fileData, mimeType, extractedData, ownerId, categoryId } = body as {
      fileName: string;
      fileData: string;
      mimeType: string;
      extractedData?: Record<string, unknown>;
      ownerId: string;
      categoryId?: string;
    };

    logger.info(MODULE_POST, 'Intentando guardar documento', {
      fileName,
      ownerId,
      userId: session.user.id,
      userRole: session.user.role,
    });

    // Validación de datos requeridos
    if (!fileName || !fileData || !mimeType || !ownerId) {
      logger.warn(MODULE_POST, 'Datos requeridos faltantes', {
        hasFileName: !!fileName,
        hasFileData: !!fileData,
        hasMimeType: !!mimeType,
        hasOwnerId: !!ownerId,
      });
      return NextResponse.json(
        { error: "Faltan datos requeridos: fileName, fileData, mimeType, ownerId" },
        { status: 400 }
      );
    }

    // Verificar permisos
    if (session.user.id !== ownerId && session.user.role !== "ADMIN") {
      logger.warn(MODULE_POST, 'Intento de guardado sin permisos', {
        userId: session.user.id,
        ownerId,
        userRole: session.user.role,
      });
      return NextResponse.json(
        { error: "No tienes permisos para guardar documentos para otro usuario" },
        { status: 403 }
      );
    }

    const result = await documentService.createDocument({
      fileName,
      fileData,
      mimeType,
      extractedData: extractedData || {},
      ownerId,
      categoryId,
    });

    logger.info(MODULE_POST, 'Documento guardado exitosamente', {
      documentId: result.id,
      fileName,
    });

    return NextResponse.json({
      success: true,
      documentId: result.id,
      fileName: fileName,
    });
  } catch (error) {
    logger.error(
      MODULE_POST,
      'Error al guardar documento',
      error instanceof Error ? error : undefined,
      { fileName: (body as any)?.fileName }
    );
    const errorMessage = error instanceof Error ? error.message : "Error desconocido";
    return NextResponse.json(
      { error: `Error al guardar documento: ${errorMessage}` },
      { status: 500 }
    );
  }
}
