/**
 * Staff N8N Integration Test API
 *
 * POST /api/staff/n8n-test - Test N8N webhook connectivity
 * GET /api/staff/n8n-test - Get N8N configuration status
 *
 * This endpoint allows staff to:
 * 1. Test the connection to N8N
 * 2. Simulate a conversation callback
 * 3. Verify webhook authentication
 *
 * N8N calls are external service calls -- they stay as-is.
 * Only user lookup is data-source routed.
 */

import { NextRequest, NextResponse } from "next/server";
import { validateStaffSession } from "@/lib/staff-session";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import { systemSettingsService } from "@/lib/services/system-settings.service";
import { getDataSource } from "@/lib/data-source";

interface N8NTestResult {
  success: boolean;
  status: "connected" | "disconnected" | "error";
  details: {
    webhookTokenConfigured: boolean;
    n8nBaseUrlConfigured: boolean;
    testUserFound: boolean;
    lastTestAt?: string;
  };
  testResults?: {
    contextLookup?: { success: boolean; message: string };
    webhookCallback?: { success: boolean; message: string };
  };
  error?: string;
}

/**
 * GET /api/staff/n8n-test
 * Check N8N configuration status
 */
export async function GET(request: NextRequest) {
  try {
    const staffSession = await validateStaffSession(request);
    if (!staffSession) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const webhookToken = await systemSettingsService.getN8NWebhookToken();
    const webhookTokenConfigured = Boolean(webhookToken);
    const n8nBaseUrl = await systemSettingsService.get("n8n.base_url");
    const n8nBaseUrlConfigured = Boolean(
      n8nBaseUrl || process.env.N8N_BASE_URL,
    );

    // Find a test user -- always Prisma for user model queries
    const _ds = getDataSource("organizations");
    void _ds;

    const testUser = await prisma.users.findFirst({
      where: {
        isActive: true,
        workflows: {
          some: { status: "active" },
        },
      },
      select: { id: true, email: true, name: true },
    });

    const result: N8NTestResult = {
      success: webhookTokenConfigured && n8nBaseUrlConfigured,
      status:
        webhookTokenConfigured && n8nBaseUrlConfigured
          ? "connected"
          : "disconnected",
      details: {
        webhookTokenConfigured,
        n8nBaseUrlConfigured,
        testUserFound: Boolean(testUser),
      },
    };

    return NextResponse.json(result);
  } catch (error) {
    logger.error("N8N test status check failed", { error });
    return NextResponse.json(
      { success: false, status: "error", error: "Failed to check status" },
      { status: 500 },
    );
  }
}

/**
 * POST /api/staff/n8n-test
 * Run N8N integration tests
 */
export async function POST(request: NextRequest) {
  try {
    const staffSession = await validateStaffSession(request);
    if (!staffSession) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const { testType, userId } = body;

    // Find test user -- always Prisma for user model
    let testUser;
    if (userId) {
      testUser = await prisma.users.findUnique({
        where: { id: userId },
        select: { id: true, email: true, name: true, n8nWebhookToken: true },
      });
    } else {
      testUser = await prisma.users.findFirst({
        where: { isActive: true },
        select: { id: true, email: true, name: true, n8nWebhookToken: true },
      });
    }

    if (!testUser) {
      return NextResponse.json(
        { success: false, error: "No test user found" },
        { status: 404 },
      );
    }

    const testResults: N8NTestResult["testResults"] = {};

    // Test 1: Context Lookup (internal call -- stays as-is)
    if (!testType || testType === "context") {
      try {
        const authToken =
          (await systemSettingsService.getN8NWebhookToken()) || "test-token";
        const contextResponse = await fetch(
          `${process.env.NEXTAUTH_URL || "http://localhost:9000"}/api/n8n/context`,
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              auth_token: authToken,
              lookup_type: "user_id",
              lookup_value: testUser.id,
              include: {
                knowledge_base: true,
                credentials: true,
                workflow_config: true,
              },
            }),
          },
        );

        const contextData = await contextResponse.json();
        testResults.contextLookup = {
          success: contextResponse.ok && contextData.success,
          message: contextResponse.ok
            ? `User "${testUser.name}" found with context`
            : contextData.error || "Context lookup failed",
        };
      } catch (error) {
        testResults.contextLookup = {
          success: false,
          message: `Error: ${error instanceof Error ? error.message : "Unknown error"}`,
        };
      }
    }

    // Test 2: Webhook Callback (internal call -- stays as-is)
    if (!testType || testType === "webhook") {
      try {
        const webhookAuthToken =
          (await systemSettingsService.getN8NWebhookToken()) || "test-token";
        const webhookResponse = await fetch(
          `${process.env.NEXTAUTH_URL || "http://localhost:9000"}/api/webhooks/n8n/conversation`,
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              auth_token: webhookAuthToken,
              user_id: testUser.id,
              platform: "whatsapp",
              customer_phone: "+974-TEST-0000",
              customer_name: "Test Customer (Staff Test)",
              message: {
                role: "system",
                content: `[N8N Integration Test] Triggered by staff at ${new Date().toISOString()}`,
                timestamp: new Date().toISOString(),
              },
            }),
          },
        );

        const webhookData = await webhookResponse.json();
        testResults.webhookCallback = {
          success: webhookResponse.ok && webhookData.success,
          message: webhookResponse.ok
            ? `Test conversation created: ${webhookData.conversation_id}`
            : webhookData.error || "Webhook callback failed",
        };
      } catch (error) {
        testResults.webhookCallback = {
          success: false,
          message: `Error: ${error instanceof Error ? error.message : "Unknown error"}`,
        };
      }
    }

    const allPassed = Object.values(testResults).every((r) => r?.success);

    logger.info("N8N integration test completed", {
      staffId: staffSession.staffId,
      testUserId: testUser.id,
      results: testResults,
    });

    return NextResponse.json({
      success: allPassed,
      status: allPassed ? "connected" : "error",
      testUser: {
        id: testUser.id,
        name: testUser.name,
        email: testUser.email,
      },
      testResults,
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    logger.error("N8N integration test failed", { error });
    return NextResponse.json(
      { success: false, status: "error", error: "Test execution failed" },
      { status: 500 },
    );
  }
}
