/**
 * Knowledge Base Single Document API
 * GET - Get document details
 * PATCH - Update document metadata
 * DELETE - Delete document
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { KnowledgeBaseService } from "@/lib/services/knowledge-base.service";
import { PineconeMultimodalService } from "@/lib/services/pinecone-multimodal.service";
import { deleteFromConvexStorage } from "@/lib/convex-storage";
import { validateCSRFToken } from "@/lib/csrf";
import { logger } from "@/lib/logger";

const scopedLogger = logger.scope("KnowledgeBaseDocumentAPI");

interface RouteParams {
  params: Promise<{ id: string }>;
}

/**
 * GET /api/dashboard/knowledge-base/documents/[id]
 * Get a single document
 */
export async function GET(request: NextRequest, { params }: RouteParams) {
  try {
    const user = await getAuthenticatedUser(request, auth);

    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const { id } = await params;
    const document = await KnowledgeBaseService.getDocument(user.userId, id);

    if (!document) {
      return NextResponse.json(
        { success: false, error: "Document not found" },
        { status: 404 },
      );
    }

    return NextResponse.json({
      success: true,
      document,
    });
  } catch (error) {
    scopedLogger.error("Failed to get document", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

/**
 * PATCH /api/dashboard/knowledge-base/documents/[id]
 * Update document metadata
 */
export async function PATCH(request: NextRequest, { params }: RouteParams) {
  try {
    const user = await getAuthenticatedUser(request, auth);

    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    if (!validateCSRFToken(request)) {
      return NextResponse.json(
        { success: false, error: "Invalid CSRF token" },
        { status: 403 },
      );
    }

    const { id } = await params;
    const body = await request.json();
    const { title, description, category } = body;

    const document = await KnowledgeBaseService.updateDocument(
      user.userId,
      id,
      {
        title,
        description,
        category,
      },
    );

    if (!document) {
      return NextResponse.json(
        { success: false, error: "Document not found" },
        { status: 404 },
      );
    }

    scopedLogger.info("Document updated", {
      userId: user.userId,
      documentId: id,
    });

    return NextResponse.json({
      success: true,
      document,
    });
  } catch (error) {
    scopedLogger.error("Failed to update document", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

/**
 * DELETE /api/dashboard/knowledge-base/documents/[id]
 * Delete a document
 */
export async function DELETE(request: NextRequest, { params }: RouteParams) {
  try {
    const user = await getAuthenticatedUser(request, auth);

    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    if (!validateCSRFToken(request)) {
      return NextResponse.json(
        { success: false, error: "Invalid CSRF token" },
        { status: 403 },
      );
    }

    const { id } = await params;

    // Get document first to retrieve storageId and embeddingId before deletion
    const document = await KnowledgeBaseService.getDocument(user.userId, id);
    if (!document) {
      return NextResponse.json(
        { success: false, error: "Document not found" },
        { status: 404 },
      );
    }

    // Delete from database
    const deleted = await KnowledgeBaseService.deleteDocument(user.userId, id);
    if (!deleted) {
      return NextResponse.json(
        { success: false, error: "Failed to delete document" },
        { status: 500 },
      );
    }

    // Delete vector from Pinecone (if embedded)
    const vectorId = `doc-${id}`;
    if (PineconeMultimodalService.isConfigured()) {
      try {
        await PineconeMultimodalService.deleteVectors(user.userId, [vectorId]);
        scopedLogger.info("Pinecone vector deleted", {
          documentId: id,
          vectorId,
        });
      } catch (pineconeError) {
        scopedLogger.warn("Failed to delete Pinecone vector", {
          documentId: id,
          error: pineconeError,
        });
      }
    }

    // Delete file from Convex storage (if storageId exists)
    const storageId = (document as unknown as Record<string, unknown>)
      .storageId as string | undefined;
    if (storageId) {
      try {
        await deleteFromConvexStorage(storageId);
        scopedLogger.info("Convex storage file deleted", {
          documentId: id,
          storageId,
        });
      } catch (storageError) {
        scopedLogger.warn("Failed to delete from Convex storage", {
          documentId: id,
          error: storageError,
        });
      }
    }

    scopedLogger.info("Document fully deleted", {
      userId: user.userId,
      documentId: id,
    });

    return NextResponse.json({
      success: true,
      message: "Document deleted successfully",
    });
  } catch (error) {
    scopedLogger.error("Failed to delete document", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
