/**
 * WhatsApp Connection Status API
 *
 * GET /api/integrations/whatsapp/status
 *
 * Returns WhatsApp connection status for authenticated user:
 * - Connection state (connected/disconnected)
 * - Phone number details (if connected)
 * - Verified business name
 * - Connection timestamp
 *
 * Security:
 * - Requires authenticated user session
 * - Only returns data for current user
 */

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

interface StatusResponse {
  connected: boolean;
  phone_number?: string;
  display_phone_number?: string;
  verified_name?: string;
  connected_at?: string;
  error?: string;
}

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

    const userId = session.user.id;

    // ── Convex data-source branch ──────────────────────────────────────
    if (getDataSource("whatsapp") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");

        interface WhatsappConfigResult {
          _id: string;
          whatsappConnected: boolean;
          whatsappNumber: string | null;
          whatsappConnectedAt: number | null;
          n8nWebhookUrl: string | null;
          n8nWorkflowId: string | null;
        }

        const config = await convexQuery<WhatsappConfigResult | null>(
          "whatsapp/queries:getWhatsappConfig",
          { email: session.user.email || undefined },
        );

        if (config) {
          const response: StatusResponse = {
            connected: config.whatsappConnected ?? false,
            phone_number: config.whatsappNumber ?? undefined,
            connected_at: config.whatsappConnectedAt
              ? new Date(config.whatsappConnectedAt).toISOString()
              : undefined,
          };
          return NextResponse.json<StatusResponse>(response, { status: 200 });
        }
        // config null → fall through to Prisma
      } catch (error) {
        console.error("[Convex fallback] whatsapp status:", error);
        // Fall through to Prisma
      }
    }

    // ── Prisma path (primary or fallback) ──────────────────────────────
    // Get connection status
    const status = await whatsappService.getConnectionStatus(userId);

    const response: StatusResponse = {
      connected: status.connected,
      phone_number: status.phoneNumber,
      display_phone_number: status.displayPhoneNumber,
      verified_name: status.verifiedName,
      connected_at: status.connectedAt?.toISOString(),
    };

    return NextResponse.json<StatusResponse>(response, { status: 200 });
  } catch (error) {
    logger.error("WhatsApp status endpoint error", error);
    return NextResponse.json<StatusResponse>(
      { connected: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

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