/**
 * WhatsApp Business Connection API
 *
 * POST /api/integrations/whatsapp/connect
 *
 * Connects user's WhatsApp Business account by:
 * 1. Validating Meta credentials
 * 2. Storing encrypted access token
 * 3. Updating user's connection status
 * 4. Auto-registering webhook with Meta
 *
 * Security:
 * - Requires authenticated user session
 * - Validates credentials with Meta API
 * - Encrypts access token with AES-256-GCM
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { whatsappService } from "@/lib/services/whatsapp.service";
import { logger } from "@/lib/logger";
import { z } from "zod";
import { getDataSource } from "@/lib/data-source";
import { registerWebhook } from "@/lib/services/whatsapp-webhook-registration";

// Request validation schema
const connectRequestSchema = z.object({
  phone_number_id: z.string().min(1, "Phone number ID is required"),
  access_token: z.string().min(1, "Access token is required"),
  waba_id: z.string().optional(),
});

interface ConnectResponse {
  success: boolean;
  message?: string;
  error?: string;
}

export async function POST(request: NextRequest) {
  try {
    // Authenticate user
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json<ConnectResponse>(
        { success: false, error: "Unauthorized. Please log in." },
        { status: 401 },
      );
    }

    const userId = session.user.id;

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

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

    const { phone_number_id, access_token, waba_id } = validationResult.data;

    logger.info("WhatsApp connection attempt", { userId });

    // Connect WhatsApp
    const result = await whatsappService.connectWhatsApp(
      userId,
      phone_number_id,
      access_token,
    );

    if (!result.success) {
      return NextResponse.json<ConnectResponse>(
        {
          success: false,
          error: result.error || "Failed to connect WhatsApp",
        },
        { status: 400 },
      );
    }

    // ── Convex data-source branch: replicate DB write to Convex ────────
    if (getDataSource("whatsapp") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");

        await convexMutation("whatsapp/mutations:updateWhatsappConfig", {
          email: session.user.email || "",
          whatsappConnected: true,
          whatsappNumber: phone_number_id,
          whatsappConnectedAt: Date.now(),
        });
      } catch (convexError) {
        console.error("[Convex replicate] whatsapp connect:", convexError);
        // Non-blocking: Prisma already succeeded
      }
    }

    // ── Auto-register webhook if WABA ID is provided ───────────────────
    if (waba_id) {
      const webhookResult = await registerWebhook(waba_id, access_token);
      if (!webhookResult.success) {
        logger.warn("Webhook auto-registration failed (non-blocking)", {
          userId,
          wabaId: waba_id,
          error: webhookResult.error,
        });
      } else {
        logger.info("Webhook auto-registered after manual connect", {
          userId,
          wabaId: waba_id,
        });
      }
    }

    logger.info("WhatsApp connected successfully", { userId });

    return NextResponse.json<ConnectResponse>(
      {
        success: true,
        message: "WhatsApp Business account connected successfully",
      },
      { status: 200 },
    );
  } catch (error) {
    logger.error("WhatsApp connection endpoint error", error);
    return NextResponse.json<ConnectResponse>(
      { 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 });
}
