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

/**
 * GET /api/documents/[id]
 * Obtener un documento por ID
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || !session.user) {
      return NextResponse.json({ error: "No autenticado" }, { status: 401 });
    }

    const { id } = await params;
    const document = await documentService.getDocumentById(id);

    if (!document) {
      return NextResponse.json(
        { error: "Documento no encontrado" },
        { status: 404 }
      );
    }

    // Verificar permisos
    if (document.ownerId !== session.user.id && session.user.role !== "ADMIN") {
      return NextResponse.json(
        { error: "No tienes permisos para ver este documento" },
        { status: 403 }
      );
    }

    return NextResponse.json({ success: true, document });
  } catch (error) {
    console.error("❌ [GET /api/documents/[id]] Error:", error);
    return NextResponse.json(
      { error: "Error al obtener documento" },
      { status: 500 }
    );
  }
}

/**
 * PUT /api/documents/[id]
 * Actualizar datos extraídos de un documento
 */
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || !session.user) {
      return NextResponse.json({ error: "No autenticado" }, { status: 401 });
    }

    const { id } = await params;
    const body = await request.json();
    const { extractedData } = body;

    await documentService.updateDocument(
      id,
      extractedData,
      session.user.id,
      session.user.role
    );

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("❌ [PUT /api/documents/[id]] Error:", error);
    const errorMessage = error instanceof Error ? error.message : "Error desconocido";
    return NextResponse.json(
      { error: errorMessage },
      { status: error instanceof Error && error.message.includes("permisos") ? 403 : 500 }
    );
  }
}

/**
 * DELETE /api/documents/[id]
 * Eliminar un documento
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || !session.user) {
      return NextResponse.json({ error: "No autenticado" }, { status: 401 });
    }

    const { id } = await params;

    await documentService.deleteDocument(
      id,
      session.user.id,
      session.user.role
    );

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("❌ [DELETE /api/documents/[id]] Error:", error);
    const errorMessage = error instanceof Error ? error.message : "Error desconocido";
    return NextResponse.json(
      { error: errorMessage },
      { status: error instanceof Error && error.message.includes("permisos") ? 403 : 500 }
    );
  }
}
