/**
 * N8N Knowledge Base Sync API
 *
 * Called by N8N workflows after uploading documents directly to Gemini.
 * Creates a record in Mawidi's database so documents appear in the dashboard.
 *
 * Flow:
 * 1. N8N uploads file to Gemini (via form trigger)
 * 2. N8N imports file to user's FileSearchStore
 * 3. N8N calls this endpoint to sync the record
 * 4. Dashboard now shows the document
 */

import { NextRequest, NextResponse } from "next/server";
import { convexQuery, convexMutation } from "@/lib/convex-client";
import { logger } from "@/lib/logger";
import { systemSettingsService } from "@/lib/services/system-settings.service";
import { n8nKBSyncSchema } from "@/lib/validators/knowledge-base.validators";

interface KBSyncResponse {
  success: boolean;
  document?: {
    id: string;
    geminiFileName: string;
    status: string;
  };
  error?: string;
}

export async function POST(request: NextRequest) {
  try {
    // Parse and validate request body
    const body = await request.json();
    const validationResult = n8nKBSyncSchema.safeParse(body);

    if (!validationResult.success) {
      return NextResponse.json<KBSyncResponse>(
        {
          success: false,
          error: "Invalid request: " + validationResult.error.errors[0].message,
        },
        { status: 400 },
      );
    }

    const {
      auth_token,
      user_id,
      gemini_file_name,
      gemini_store_name,
      original_name,
      mime_type,
      file_size,
      title,
      category,
    } = validationResult.data;

    // Validate auth token
    const isValidToken =
      await systemSettingsService.validateN8NToken(auth_token);
    if (!isValidToken) {
      logger.warn("N8N KB sync - invalid auth token", { user_id });
      return NextResponse.json<KBSyncResponse>(
        { success: false, error: "Invalid authentication token" },
        { status: 401 },
      );
    }

    // Verify user has knowledge base settings (validates user exists)
    const kbSettings = await convexQuery<{
      _id: string;
      prismaId?: string;
      geminiFileSearchStoreName?: string;
      geminiFileSearchStoreId?: string;
    }>("voice_agents/queries:getKBSettingsByUserId", { userId: user_id });

    if (!kbSettings) {
      return NextResponse.json<KBSyncResponse>(
        { success: false, error: "User not found or inactive" },
        { status: 404 },
      );
    }

    // Check if document already exists (by Gemini file name) via Convex
    const allDocs = await convexQuery<Array<{
      _id: string;
      prismaId?: string;
      geminiFileName?: string;
      status: string;
      deletedAt?: number;
    }>>("voice_agents/queries:getKBDocuments", { userId: user_id });
    const existingDoc = (allDocs ?? []).find(
      (d) => d.geminiFileName === gemini_file_name && !d.deletedAt,
    );

    if (existingDoc) {
      logger.info("N8N KB sync - document already exists", {
        user_id,
        gemini_file_name,
        document_id: existingDoc.prismaId ?? existingDoc._id,
      });
      return NextResponse.json<KBSyncResponse>({
        success: true,
        document: {
          id: existingDoc.prismaId ?? existingDoc._id,
          geminiFileName: existingDoc.geminiFileName!,
          status: existingDoc.status,
        },
      });
    }

    // Create document record in Convex
    const now = Date.now();

    const convexDocId = await convexMutation<string>(
      "voice_agents/mutations:createKBDocument",
      {
        userId: user_id,
        filename: gemini_file_name.replace("files/", ""), // Store just the ID part
        originalName: original_name,
        mimeType: mime_type,
        fileSize: file_size,
        storagePath: `gemini:${gemini_file_name}`, // Mark as Gemini-hosted
        title: title || original_name,
        category: category || "general",
      },
    );

    if (!convexDocId) {
      return NextResponse.json<KBSyncResponse>(
        { success: false, error: "Failed to create document record" },
        { status: 500 },
      );
    }

    // Update to COMPLETED status + Gemini metadata (createKBDocument defaults to PENDING)
    await convexMutation("voice_agents/mutations:updateKBDocument", {
      id: convexDocId,
      status: "COMPLETED",
      processedAt: now,
      geminiFileName: gemini_file_name,
      geminiUploadedAt: now,
    });

    // Update the user's KB settings with the store name if not set
    if (kbSettings && !kbSettings.geminiFileSearchStoreName) {
      await convexMutation("voice_agents/mutations:updateKBSettings", {
        id: kbSettings._id,
        geminiFileSearchStoreName: gemini_store_name,
        geminiFileSearchStoreId: gemini_store_name.replace(
          "fileSearchStores/",
          "",
        ),
      });
    }

    logger.info("N8N KB sync completed", {
      user_id,
      document_id: convexDocId,
      gemini_file_name,
      gemini_store_name,
      original_name,
    });

    return NextResponse.json<KBSyncResponse>(
      {
        success: true,
        document: {
          id: convexDocId,
          geminiFileName: gemini_file_name,
          status: "COMPLETED",
        },
      },
      { status: 201 },
    );
  } catch (error) {
    logger.error("N8N KB sync error", { error });
    return NextResponse.json<KBSyncResponse>(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

// Only allow POST method
export async function GET() {
  return NextResponse.json({ error: "Method not allowed" }, { status: 405 });
}
