/**
 * WhatsApp Conversation Logging API
 * POST /api/whatsapp/conversations/log
 *
 * Logs WhatsApp conversation messages to database.
 * Called by n8n workflow after each conversation turn.
 */

import { NextRequest, NextResponse } from "next/server";
import { logConversation } from "@/lib/services/whatsapp-conversations.service";
import { ConversationLogSchema } from "@/lib/validators/whatsapp-ai.validator";
import { systemSettingsService } from "@/lib/services/system-settings.service";
import { logger } from "@/lib/logger";
import { convexMutation } from "@/lib/convex-client";
import { corsResponse } from "@/lib/cors";

export async function POST(request: NextRequest) {
  try {
    // Authenticate caller via n8n token
    const authHeader = request.headers.get("authorization");
    const token = authHeader?.replace("Bearer ", "");
    if (!token) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    const isValid = await systemSettingsService.validateN8NToken(token);
    if (!isValid) {
      return NextResponse.json({ error: "Invalid token" }, { status: 401 });
    }

    const body = await request.json();

    // Validate input
    const validation = ConversationLogSchema.safeParse(body);

    if (!validation.success) {
      return NextResponse.json(
        {
          error: "Invalid request",
          details: validation.error.errors,
        },
        { status: 400 },
      );
    }

    const input = validation.data;

    // Log conversation via Convex
    const conversationId = await convexMutation(
      "whatsapp/mutations:createOrgConversation",
      {
        organizationId: input.organizationId,
        userPhone: input.userPhone,
        userName: input.userName ?? undefined,
        language: input.language ?? "en",
      },
    );

    // Log each message in the conversation
    for (const msg of input.messages) {
      await convexMutation("whatsapp/mutations:sendOrgMessage", {
        conversationId: conversationId as string,
        role: msg.role,
        content: msg.content,
        language: msg.language ?? "en",
        intent: msg.intent ?? undefined,
        toolsUsed: msg.toolsUsed ?? [],
        metadata: msg.metadata ?? undefined,
      });
    }

    logger.info("Conversation logged", {
      conversationId,
      organizationId: input.organizationId,
      userPhone: input.userPhone,
      messageCount: input.messages.length,
    });

    return NextResponse.json({
      success: true,
      data: {
        conversationId,
        messageCount: input.messages.length,
      },
    });
  } catch (error) {
    logger.error("Conversation logging error", { error });

    return NextResponse.json(
      {
        error: "Internal server error",
        message:
          error instanceof Error ? error.message : "Failed to log conversation",
      },
      { status: 500 },
    );
  }
}

// OPTIONS for CORS preflight
export async function OPTIONS() {
  return corsResponse("POST, OPTIONS");
}
