/**
 * N8N Analytics Webhook Callback
 *
 * Receives batch analytics updates from N8N workflows.
 * Used for daily rollups and aggregated metrics.
 */

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import { systemSettingsService } from "@/lib/services/system-settings.service";
import { z } from "zod";
import { applyRateLimit, rateLimiters, getClientIdentifier } from "@/lib/rate-limiter";

// Request validation schema
const analyticsPayloadSchema = z.object({
  auth_token: z.string().min(1),
  user_id: z.string().min(1),
  workflow_type: z.string().min(1),
  date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Date must be YYYY-MM-DD"),
  metrics: z.object({
    messages_received: z.number().min(0).optional(),
    messages_sent: z.number().min(0).optional(),
    appointments_booked: z.number().min(0).optional(),
    quotations_sent: z.number().min(0).optional(),
    leads_generated: z.number().min(0).optional(),
  }),
});

interface AnalyticsCallbackResponse {
  success: boolean;
  error?: string;
}

export async function POST(request: NextRequest) {
  // Rate limit webhook requests (100/min per IP)
  const rateLimitResponse = await applyRateLimit(request, rateLimiters.webhookGeneral);
  if (rateLimitResponse) {
    logger.warn("N8N analytics webhook rate limit exceeded", {
      ip: getClientIdentifier(request),
    });
    return rateLimitResponse;
  }

  try {
    // Parse and validate request body
    const body = await request.json();
    const validationResult = analyticsPayloadSchema.safeParse(body);

    if (!validationResult.success) {
      logger.warn("N8N analytics callback - invalid payload", {
        errors: validationResult.error.errors,
      });
      return NextResponse.json<AnalyticsCallbackResponse>(
        {
          success: false,
          error: "Invalid payload: " + validationResult.error.errors[0].message,
        },
        { status: 400 },
      );
    }

    const payload = validationResult.data;

    // Validate auth token (from database or env fallback)
    const isValidToken = await systemSettingsService.validateN8NToken(
      payload.auth_token,
    );
    if (!isValidToken) {
      logger.warn("N8N analytics callback - invalid auth token", {
        user_id: payload.user_id,
      });
      return NextResponse.json<AnalyticsCallbackResponse>(
        { success: false, error: "Invalid authentication token" },
        { status: 401 },
      );
    }

    // Verify user exists
    const user = await prisma.users.findUnique({
      where: { id: payload.user_id },
      select: { id: true, isActive: true },
    });

    if (!user) {
      logger.warn("N8N analytics callback - user not found", {
        user_id: payload.user_id,
      });
      return NextResponse.json<AnalyticsCallbackResponse>(
        { success: false, error: "User not found" },
        { status: 404 },
      );
    }

    // Parse date
    const [year, month, day] = payload.date.split("-").map(Number);
    const date = new Date(year, month - 1, day);

    // Upsert analytics record
    await prisma.workflowAnalytics.upsert({
      where: {
        userId_workflowType_date: {
          userId: payload.user_id,
          workflowType: payload.workflow_type,
          date,
        },
      },
      create: {
        userId: payload.user_id,
        workflowType: payload.workflow_type,
        date,
        messagesReceived: payload.metrics.messages_received || 0,
        messagesSent: payload.metrics.messages_sent || 0,
        appointmentsBooked: payload.metrics.appointments_booked || 0,
        quotationsSent: payload.metrics.quotations_sent || 0,
        leadsGenerated: payload.metrics.leads_generated || 0,
      },
      update: {
        messagesReceived:
          payload.metrics.messages_received !== undefined
            ? { increment: payload.metrics.messages_received }
            : undefined,
        messagesSent:
          payload.metrics.messages_sent !== undefined
            ? { increment: payload.metrics.messages_sent }
            : undefined,
        appointmentsBooked:
          payload.metrics.appointments_booked !== undefined
            ? { increment: payload.metrics.appointments_booked }
            : undefined,
        quotationsSent:
          payload.metrics.quotations_sent !== undefined
            ? { increment: payload.metrics.quotations_sent }
            : undefined,
        leadsGenerated:
          payload.metrics.leads_generated !== undefined
            ? { increment: payload.metrics.leads_generated }
            : undefined,
      },
    });

    logger.info("N8N analytics callback - updated metrics", {
      user_id: payload.user_id,
      workflow_type: payload.workflow_type,
      date: payload.date,
      metrics: payload.metrics,
    });

    return NextResponse.json<AnalyticsCallbackResponse>({
      success: true,
    });
  } catch (error) {
    logger.error("N8N analytics callback error", { error });
    return NextResponse.json<AnalyticsCallbackResponse>(
      { 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 });
}
