/**
 * WhatsApp Business Cloud API Webhook
 *
 * Handles webhook callbacks from Meta for:
 * - Initial webhook verification (GET)
 * - Incoming WhatsApp messages (POST)
 * - Message status updates (POST)
 *
 * Security:
 * - HMAC-SHA256 signature verification
 * - Verify token validation
 * - Payload sanitization
 * - Input sanitization via DOMPurify
 *
 * Flow (POST):
 * 1. Rate-limit & verify webhook signature
 * 2. Parse payload & optionally store in Convex
 * 3. Resolve organization via whatsAppRouter
 * 4. Language detection / selection flow
 * 5. Human-handoff check (30-min window)
 * 6. Process via sector-aware AI engine
 * 7. Send response via Meta Cloud API
 */

import { NextRequest, NextResponse } from "next/server";
import { whatsappService } from "@/lib/services/whatsapp.service";
import { getDataSource } from "@/lib/data-source";
import { logger } from "@/lib/logger";
import { applyRateLimit, rateLimiters, getClientIdentifier } from "@/lib/rate-limiter";
import { whatsAppRouter } from "@/lib/services/whatsapp-router.service";
import { getSectorConfigForIndustry } from "@/lib/config/sector-registry";
import { orgWhatsAppKeysService } from "@/lib/services/org-whatsapp-keys.service";
import { whatsAppAIEngine } from "@/lib/services/whatsapp-ai-engine.service";
import { analyzeConversationTurn } from "@/lib/services/conversation-learning.service";
import {
  sanitizeChatMessage,
  sanitizePhoneNumber,
} from "@/lib/sanitizers/chat.sanitizer";
import {
  getLanguagePreference,
  setLanguagePreference,
} from "@/lib/services/whatsapp-language.service";
import { buildGreetingForOrg } from "@/lib/services/whatsapp-greeting.service";
import { qatariDialectService } from "@/lib/services/qatari-dialect.service";
import { prisma } from "@/lib/db";
import type {
  ConversationContext,
  BookingFlowState,
} from "@/lib/types/twilio-whatsapp.types";

// =============================================================================
// Arabic detection helper
// =============================================================================

const ARABIC_RANGE = /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF]/;

function detectLanguage(text: string): "en" | "ar" {
  const arabicChars = (text.match(new RegExp(ARABIC_RANGE.source, "g")) || [])
    .length;
  return arabicChars > text.length * 0.3 ? "ar" : "en";
}

// =============================================================================
// Meta Cloud API helper — send a text message
// =============================================================================

async function sendMetaTextMessage(
  phoneNumberId: string,
  accessToken: string,
  to: string,
  body: string,
): Promise<{ success: boolean; error?: string }> {
  try {
    const sendUrl = `https://graph.facebook.com/v19.0/${phoneNumberId}/messages`;
    const response = await fetch(sendUrl, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${accessToken}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        messaging_product: "whatsapp",
        to,
        type: "text",
        text: { body },
      }),
    });

    if (!response.ok) {
      const errorBody = await response.text();
      logger.error("Meta Cloud API send failed", {
        status: response.status,
        body: errorBody,
        to: to.slice(-4),
      });
      return { success: false, error: `Meta API ${response.status}` };
    }

    return { success: true };
  } catch (error) {
    logger.error("Meta Cloud API send exception", { error, to: to.slice(-4) });
    return {
      success: false,
      error: error instanceof Error ? error.message : "Send failed",
    };
  }
}

// =============================================================================
// Process a single incoming message through the AI engine
// =============================================================================

async function processIncomingMessage(
  phoneNumberId: string,
  msg: Record<string, unknown>,
  contacts: Array<{ profile?: { name?: string } }>,
): Promise<void> {
  // ── Resolve organization ─────────────────────────────────
  const org = await whatsAppRouter.resolveOrganization(phoneNumberId);
  if (!org) {
    logger.info("WhatsApp webhook: no org for phone_number_id, ignoring", {
      phoneNumberId,
    });
    return;
  }

  // ── Resolve display name from owner's companyName ────
  let displayName = org.name;
  try {
    const { convexQuery: cq } = await import("@/lib/convex-client");
    const ownerUser = await cq<{ companyName?: string } | null>(
      "auth/queries:getUser",
      { id: org.ownerId },
    );
    if (ownerUser?.companyName) displayName = ownerUser.companyName;
  } catch {
    // non-blocking — fall back to org.name
  }

  // ── Get sector config ────────────────────────────────────
  const sectorConfig = getSectorConfigForIndustry(org.industry ?? "general");

  // ── Get decrypted credentials ────────────────────────────
  const credentials =
    await orgWhatsAppKeysService.getDecryptedCredentials(org.id);
  if (!credentials) {
    logger.error("WhatsApp webhook: no credentials for org", {
      organizationId: org.id,
    });
    return;
  }

  // ── Extract message data ─────────────────────────────────
  const rawMessageText =
    (msg.text as { body?: string } | undefined)?.body ??
    (msg.type as string) ??
    "";
  const customerPhoneRaw = (msg.from as string) ?? "";
  const customerNameRaw = contacts?.[0]?.profile?.name ?? "";

  const messageText = sanitizeChatMessage(rawMessageText);
  const customerPhone = sanitizePhoneNumber(customerPhoneRaw);

  if (!customerPhone) {
    logger.warn("WhatsApp webhook: empty phone after sanitization", {
      organizationId: org.id,
    });
    return;
  }

  if (!messageText) {
    logger.debug("WhatsApp webhook: empty message after sanitization", {
      organizationId: org.id,
      from: customerPhone,
    });
    return;
  }

  // ── Detect language ──────────────────────────────────────
  let language = detectLanguage(messageText);

  // ── Upsert conversation ──────────────────────────────────
  let conversation = await prisma.org_whatsapp_conversations.findFirst({
    where: { organizationId: org.id, userPhone: customerPhone },
  });

  const isNewConversation = !conversation;

  if (!conversation) {
    conversation = await prisma.org_whatsapp_conversations.create({
      data: {
        organizationId: org.id,
        userPhone: customerPhone,
        userName: sanitizeChatMessage(customerNameRaw) || null,
        language,
        status: "active",
        lastMessageAt: new Date(),
        messageCount: 0,
        updatedAt: new Date(),
      },
    });
  }

  // ── Override language with stored preference ─────────────
  let storedLanguagePreference: string | null = null;
  try {
    storedLanguagePreference = await getLanguagePreference(
      org.id,
      customerPhone,
    );
    if (
      storedLanguagePreference === "en" ||
      storedLanguagePreference === "ar"
    ) {
      language = storedLanguagePreference;
    }
  } catch (err) {
    logger.warn(
      "Failed to fetch language preference, falling back to detection",
      {
        organizationId: org.id,
        error: err instanceof Error ? err.message : "Unknown error",
      },
    );
  }

  // ── Bypass selecting_language if stored preference exists ──
  const conversationStateRaw =
    (conversation.conversationState as BookingFlowState | null) ?? null;
  let bypassedLanguageSelection = false;

  if (
    storedLanguagePreference &&
    conversationStateRaw?.phase === "selecting_language"
  ) {
    await prisma.org_whatsapp_conversations.update({
      where: { id: conversation.id },
      data: {
        conversationState: JSON.parse(JSON.stringify({ phase: "idle" })),
        language,
        updatedAt: new Date(),
      },
    });
    bypassedLanguageSelection = true;
  }

  // ── First-message bilingual greeting ─────────────────────
  if (isNewConversation && !storedLanguagePreference) {
    await prisma.org_whatsapp_messages.create({
      data: {
        conversationId: conversation.id,
        role: "user",
        content: messageText,
        language,
        timestamp: new Date(),
      },
    });

    const greeting = await buildGreetingForOrg(org.id, displayName);

    if (!greeting.text) {
      // Owner opted out of automatic greetings — skip and transition to idle
      await prisma.org_whatsapp_conversations.update({
        where: { id: conversation.id },
        data: {
          conversationState: JSON.parse(JSON.stringify({ phase: "idle" })),
          lastMessageAt: new Date(),
          messageCount: { increment: 1 },
          updatedAt: new Date(),
        },
      });

      logger.info("WhatsApp webhook: greeting opted out, skipping", {
        organizationId: org.id,
        conversationId: conversation.id,
      });

      return;
    }

    await sendMetaTextMessage(
      credentials.phoneNumberId,
      credentials.accessToken,
      customerPhone,
      greeting.text,
    );

    await prisma.org_whatsapp_messages.create({
      data: {
        conversationId: conversation.id,
        role: "assistant",
        content: greeting.text,
        language: "ar",
        timestamp: new Date(),
      },
    });

    await prisma.org_whatsapp_conversations.update({
      where: { id: conversation.id },
      data: {
        conversationState: JSON.parse(
          JSON.stringify({
            phase: greeting.requiresLanguageSelection
              ? "selecting_language"
              : "idle",
          }),
        ),
        lastMessageAt: new Date(),
        messageCount: { increment: 1 },
        updatedAt: new Date(),
      },
    });

    logger.info("WhatsApp webhook: sent greeting to new user", {
      organizationId: org.id,
      conversationId: conversation.id,
      requiresLanguageSelection: greeting.requiresLanguageSelection,
    });

    return;
  }

  // ── Language selection handler ────────────────────────────
  const conversationState = conversationStateRaw;

  if (
    !bypassedLanguageSelection &&
    conversationState?.phase === "selecting_language"
  ) {
    await prisma.org_whatsapp_messages.create({
      data: {
        conversationId: conversation.id,
        role: "user",
        content: messageText,
        language,
        timestamp: new Date(),
      },
    });

    const normalized = messageText.toLowerCase().trim();
    const arabicChars = (
      messageText.match(new RegExp(ARABIC_RANGE.source, "g")) || []
    ).length;
    const isArabicChoice =
      normalized === "1" ||
      normalized === "arabic" ||
      normalized === "\u0639\u0631\u0628\u064A" ||
      normalized === "\u0639\u0631\u0628\u064A\u0629" ||
      arabicChars > messageText.length * 0.5;
    const isEnglishChoice =
      normalized === "2" || normalized === "english" || normalized === "eng";

    if (!isArabicChoice && !isEnglishChoice) {
      const reprompt =
        `\u0644\u0648 \u0633\u0645\u062D\u062A \u0627\u062E\u062A\u0631 \u0631\u0642\u0645 1 \u0623\u0648 2 \uD83D\uDC47\n` +
        `Please reply with 1 or 2 \uD83D\uDC47\n\n` +
        `1\uFE0F\u20E3 \u0627\u0644\u0639\u0631\u0628\u064A\u0629 (Arabic)\n` +
        `2\uFE0F\u20E3 English`;

      await sendMetaTextMessage(
        credentials.phoneNumberId,
        credentials.accessToken,
        customerPhone,
        reprompt,
      );

      await prisma.org_whatsapp_messages.create({
        data: {
          conversationId: conversation.id,
          role: "assistant",
          content: reprompt,
          language: "ar",
          timestamp: new Date(),
        },
      });

      await prisma.org_whatsapp_conversations.update({
        where: { id: conversation.id },
        data: {
          lastMessageAt: new Date(),
          messageCount: { increment: 1 },
          updatedAt: new Date(),
        },
      });

      return;
    }

    const selectedLanguage: "en" | "ar" = isArabicChoice ? "ar" : "en";

    try {
      await setLanguagePreference(org.id, customerPhone, selectedLanguage);
    } catch (err) {
      logger.error("Failed to save language preference", {
        organizationId: org.id,
        error: err instanceof Error ? err.message : "Unknown error",
      });
    }

    await prisma.org_whatsapp_conversations.update({
      where: { id: conversation.id },
      data: {
        language: selectedLanguage,
        conversationState: JSON.parse(JSON.stringify({ phase: "idle" })),
        lastMessageAt: new Date(),
        messageCount: { increment: 1 },
        updatedAt: new Date(),
      },
    });

    const confirmationText =
      selectedLanguage === "ar"
        ? `\u0645\u0645\u062A\u0627\u0632! \u0628\u0646\u062A\u0648\u0627\u0635\u0644 \u0645\u0639\u0627\u0643 \u0628\u0627\u0644\u0639\u0631\u0628\u064A. \u0634\u0644\u0648\u0646 \u0646\u0642\u062F\u0631 \u0646\u0633\u0627\u0639\u062F\u0643 \u0627\u0644\u064A\u0648\u0645\u061F`
        : "Great! We'll communicate in English. How can we help you today?";

    await sendMetaTextMessage(
      credentials.phoneNumberId,
      credentials.accessToken,
      customerPhone,
      confirmationText,
    );

    await prisma.org_whatsapp_messages.create({
      data: {
        conversationId: conversation.id,
        role: "assistant",
        content: confirmationText,
        language: selectedLanguage,
        timestamp: new Date(),
      },
    });

    logger.info("WhatsApp webhook: language selected", {
      organizationId: org.id,
      conversationId: conversation.id,
      language: selectedLanguage,
    });

    return;
  }

  // ── Human handoff check (30-min window) ──────────────────
  if (conversation.humanControlled) {
    const thirtyMinAgo = new Date(Date.now() - 30 * 60 * 1000);
    const stillActive =
      conversation.humanControlledAt &&
      new Date(conversation.humanControlledAt) > thirtyMinAgo;

    if (stillActive) {
      await prisma.org_whatsapp_messages.create({
        data: {
          conversationId: conversation.id,
          role: "user",
          content: messageText,
          language,
          timestamp: new Date(),
        },
      });

      await prisma.org_whatsapp_conversations.update({
        where: { id: conversation.id },
        data: {
          lastMessageAt: new Date(),
          messageCount: { increment: 1 },
          updatedAt: new Date(),
        },
      });

      logger.info("WhatsApp webhook: human-controlled, skipping AI", {
        organizationId: org.id,
        conversationId: conversation.id,
      });

      return;
    } else {
      // 30-min window expired, release back to AI
      await prisma.org_whatsapp_conversations.update({
        where: { id: conversation.id },
        data: {
          humanControlled: false,
          humanControlledAt: null,
          humanControlledBy: null,
          updatedAt: new Date(),
        },
      });
    }
  }

  // ── Load message history (last 20) ───────────────────────
  const recentMessages = await prisma.org_whatsapp_messages.findMany({
    where: { conversationId: conversation.id },
    orderBy: { timestamp: "desc" },
    take: 20,
  });

  // ── Store inbound message ────────────────────────────────
  await prisma.org_whatsapp_messages.create({
    data: {
      conversationId: conversation.id,
      role: "user",
      content: messageText,
      language,
      timestamp: new Date(),
    },
  });

  // ── Build conversation context ───────────────────────────
  const conversationHistory = recentMessages.reverse().map(
    (m: { role: string; content: string; timestamp: Date }) => ({
      role: m.role as "user" | "assistant",
      content: m.content,
      timestamp: m.timestamp,
    }),
  );

  const context: ConversationContext = {
    organizationId: org.id,
    organizationName: displayName,
    customerPhone,
    customerName:
      sanitizeChatMessage(customerNameRaw) ||
      conversation.userName ||
      undefined,
    customerEmail: conversation.customerEmail || undefined,
    language,
    conversationHistory,
    conversationState:
      (conversation.conversationState as BookingFlowState | null) ?? null,
    isReturningCustomer: conversation.messageCount > 0,
    industry: org.industry ?? undefined,
    sector: sectorConfig.key,
  };

  // ── Process via AI engine ────────────────────────────────
  const result = await whatsAppAIEngine.processMessage(context, messageText);

  // ── Guard against empty AI response ──────────────────────
  if (!result.responseText) {
    result.responseText =
      language === "ar"
        ? `\u0623\u0646\u0627 \u0647\u0646\u0627 \u0644\u0645\u0633\u0627\u0639\u062F\u062A\u0643. \u0634\u0644\u0648\u0646 \u0623\u0642\u062F\u0631 \u0623\u0633\u0627\u0639\u062F\u0643\u061F`
        : "I'm here to help. How can I assist you?";
  }

  // ── Qatari dialect post-processing ───────────────────────
  if (language === "ar") {
    try {
      const urlLineRegex = /^.*https?:\/\/\S+.*$/gm;
      const linkLines = result.responseText.match(urlLineRegex) || [];
      const textForTranslation =
        linkLines.length > 0
          ? result.responseText
              .replace(urlLineRegex, "")
              .replace(/\n{3,}/g, "\n\n")
              .trim()
          : result.responseText;

      const qatariResult =
        await qatariDialectService.translateToQatari(textForTranslation);
      if (qatariResult.translation) {
        result.responseText =
          linkLines.length > 0
            ? qatariResult.translation + "\n\n" + linkLines.join("\n")
            : qatariResult.translation;
      }
    } catch (err) {
      logger.warn("Qatari dialect translation failed, using original", {
        organizationId: org.id,
        error: err instanceof Error ? err.message : "Unknown error",
      });
    }
  }

  // ── Store outbound message ───────────────────────────────
  await prisma.org_whatsapp_messages.create({
    data: {
      conversationId: conversation.id,
      role: "assistant",
      content: result.responseText,
      language,
      intent: result.intent,
      timestamp: new Date(),
      // Phase 5: conversation learning metadata
      kbUsed: result.kbUsed ?? false,
      kbConfidence: result.kbConfidence ?? 0,
      escalatedToHuman: result.escalatedToHuman ?? false,
    },
  });

  // ── Conversation learning (Phase 5) — non-blocking ───────
  // Track unanswered/low-confidence questions to improve the KB over time.
  // The service swallows its own errors; we add .catch as defense in depth
  // and explicitly do NOT await — learning must never delay the response.
  void analyzeConversationTurn({
    organizationId: org.id,
    sector: org.sector ?? undefined,
    language,
    customerQuestion: messageText,
    kbUsed: result.kbUsed ?? false,
    kbConfidence: result.kbConfidence ?? 0,
    intent: result.intent,
    escalatedToHuman: result.escalatedToHuman ?? false,
  }).catch((err) => {
    // Non-blocking — never break the conversation
    logger.error("[learning] analyzeConversationTurn failed", {
      organizationId: org.id,
      error: err instanceof Error ? err.message : String(err),
    });
  });

  // ── Update conversation state ────────────────────────────
  await prisma.org_whatsapp_conversations.update({
    where: { id: conversation.id },
    data: {
      lastMessageAt: new Date(),
      messageCount: { increment: 1 },
      ...(result.newState
        ? { conversationState: JSON.parse(JSON.stringify(result.newState)) }
        : {}),
      updatedAt: new Date(),
    },
  });

  // ── Send response via Meta Cloud API ─────────────────────
  const sendResult = await sendMetaTextMessage(
    credentials.phoneNumberId,
    credentials.accessToken,
    customerPhone,
    result.responseText,
  );

  if (!sendResult.success) {
    logger.error("Failed to send WhatsApp response via Meta", {
      organizationId: org.id,
      error: sendResult.error,
    });
  }

  logger.info("WhatsApp message processed via local AI engine", {
    organizationId: org.id,
    sector: sectorConfig.key,
    intent: result.intent,
    phone: customerPhone.slice(-4),
    messageId: msg.id as string,
  });
}

// =============================================================================
// GET handler for webhook verification
// Called by Meta during webhook setup
// =============================================================================

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const mode = searchParams.get("hub.mode");
    const token = searchParams.get("hub.verify_token");
    const challenge = searchParams.get("hub.challenge");

    logger.info("WhatsApp webhook verification attempt", {
      mode,
      hasToken: !!token,
      hasChallenge: !!challenge,
    });

    if (!mode || !token || !challenge) {
      logger.warn("WhatsApp webhook verification - missing parameters");
      return NextResponse.json(
        { error: "Missing required parameters" },
        { status: 400 },
      );
    }

    const result = whatsappService.verifyWebhook(mode, token, challenge);

    if (!result.isValid) {
      logger.warn("WhatsApp webhook verification failed", {
        error: result.error,
      });
      return NextResponse.json(
        { error: result.error || "Verification failed" },
        { status: 403 },
      );
    }

    logger.info("WhatsApp webhook verified successfully");
    return new NextResponse(result.challenge, {
      status: 200,
      headers: { "Content-Type": "text/plain" },
    });
  } catch (error) {
    logger.error("WhatsApp webhook verification error", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}

// =============================================================================
// POST handler for incoming messages and status updates
// =============================================================================

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("WhatsApp webhook rate limit exceeded", {
      ip: getClientIdentifier(request),
    });
    return rateLimitResponse;
  }

  try {
    // Get raw body for signature verification
    const body = await request.text();
    const signature = request.headers.get("x-hub-signature-256");

    // Verify webhook signature
    const isValidSignature = whatsappService.verifyWebhookSignature(
      body,
      signature,
    );

    if (!isValidSignature) {
      logger.security("WhatsApp webhook signature verification failed", {
        hasSignature: !!signature,
        bodyLength: body.length,
      });
      return NextResponse.json({ error: "Invalid signature" }, { status: 403 });
    }

    // Parse payload
    let payload: Record<string, unknown>;
    try {
      payload = JSON.parse(body);
    } catch {
      logger.warn("WhatsApp webhook - invalid JSON payload");
      return NextResponse.json(
        { error: "Invalid JSON payload" },
        { status: 400 },
      );
    }

    // Validate payload structure
    if (!payload.object || payload.object !== "whatsapp_business_account") {
      logger.warn("WhatsApp webhook - invalid object type", {
        object: payload.object,
      });
      return NextResponse.json(
        { error: "Invalid object type" },
        { status: 400 },
      );
    }

    if (process.env.NODE_ENV === "development") {
      logger.debug("WhatsApp webhook received", {
        entries: (payload.entry as unknown[])?.length || 0,
      });
    }

    // ── Convex data-source branch: store incoming message in Convex ───
    if (getDataSource("whatsapp") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");

        for (const entry of (payload.entry as Array<Record<string, unknown>>) || []) {
          for (const change of (entry.changes as Array<Record<string, unknown>>) || []) {
            if (change.field !== "messages") continue;
            const value = change.value as Record<string, unknown>;
            const messages = value.messages as Array<Record<string, unknown>> | undefined;
            if (messages && messages.length > 0) {
              for (const msg of messages) {
                const metadata = value.metadata as Record<string, unknown> | undefined;
                const pnId = (metadata?.phone_number_id as string) || "";
                const contacts = value.contacts as Array<{ profile?: { name?: string } }> | undefined;
                await convexMutation(
                  "whatsapp/mutations:handleIncomingMessage",
                  {
                    userId: pnId,
                    customerPhone: (msg.from as string) || "",
                    customerName: contacts?.[0]?.profile?.name,
                    message: (msg.text as { body?: string })?.body || (msg.type as string) || "",
                    metadata: {
                      messageId: msg.id as string,
                      timestamp: msg.timestamp as string,
                      type: msg.type as string,
                    },
                  },
                );
              }
            }
          }
        }
      } catch (convexError) {
        console.error("[Convex replicate] whatsapp webhook:", convexError);
        // Non-blocking: continue to local AI processing
      }
    }

    // ── Process messages through local AI engine ─────────────────────
    for (const entry of (payload.entry as Array<Record<string, unknown>>) || []) {
      for (const change of (entry.changes as Array<Record<string, unknown>>) || []) {
        if (change.field !== "messages") continue;

        const value = change.value as Record<string, unknown>;
        const messages = value.messages as Array<Record<string, unknown>> | undefined;
        if (!messages || messages.length === 0) continue;

        const metadata = value.metadata as Record<string, unknown> | undefined;
        const phoneNumberId = (metadata?.phone_number_id as string) || "";
        const contacts = (value.contacts as Array<{ profile?: { name?: string } }>) || [];

        for (const msg of messages) {
          try {
            await processIncomingMessage(phoneNumberId, msg, contacts);
          } catch (msgError) {
            logger.error("Failed to process individual WhatsApp message", {
              phoneNumberId,
              messageId: msg.id as string,
              error: msgError,
            });
            // Continue processing other messages
          }
        }
      }
    }

    // Success - return 200 to acknowledge receipt
    return NextResponse.json({ received: true }, { status: 200 });
  } catch (error) {
    logger.error("WhatsApp webhook processing error", error);
    // Return 200 to prevent Meta from retrying
    return NextResponse.json(
      { received: true, error: "Processing failed" },
      { status: 200 },
    );
  }
}

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