/**
 * WhatsApp Greeting Dashboard API
 *
 * GET   /api/dashboard/whatsapp-greeting?organizationId=...
 *   Returns the org's current custom greeting fields:
 *   - greetingMessageEn
 *   - greetingMessageAr
 *   - autoGreetingEnabled
 *
 * PATCH /api/dashboard/whatsapp-greeting
 *   Updates one or more of the same fields. Request body:
 *   {
 *     organizationId: string,
 *     greetingMessageEn?: string | null,
 *     greetingMessageAr?: string | null,
 *     autoGreetingEnabled?: boolean,
 *   }
 *
 * Auth & ownership:
 *   - Requires authenticated user
 *   - User must be the organization's owner
 *   - PATCH requires a valid CSRF token
 */

import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { validateCSRFToken } from "@/lib/csrf";
import { rateLimiters, applyRateLimit } from "@/lib/rate-limiter";
import { logger } from "@/lib/logger";
import prisma from "@/lib/db";
import { convexMutation } from "@/lib/convex-client";

const scopedLogger = logger.scope("WhatsAppGreetingAPI");

const MAX_GREETING_LENGTH = 2000;

const patchSchema = z.object({
  organizationId: z.string().min(1, "organizationId is required"),
  greetingMessageEn: z
    .string()
    .max(MAX_GREETING_LENGTH, `Greeting must be ${MAX_GREETING_LENGTH} characters or fewer`)
    .optional()
    .nullable(),
  greetingMessageAr: z
    .string()
    .max(MAX_GREETING_LENGTH, `Greeting must be ${MAX_GREETING_LENGTH} characters or fewer`)
    .optional()
    .nullable(),
  autoGreetingEnabled: z.boolean().optional(),
});

// =============================================================================
// GET — fetch current greeting
// =============================================================================

export async function GET(request: NextRequest) {
  try {
    const rateLimitResponse = await applyRateLimit(
      request,
      rateLimiters.authGeneral,
    );
    if (rateLimitResponse) return rateLimitResponse;

    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const url = new URL(request.url);
    const organizationId = url.searchParams.get("organizationId");
    if (!organizationId) {
      return NextResponse.json(
        { success: false, error: "organizationId is required" },
        { status: 400 },
      );
    }

    // Verify the authenticated user owns this org
    const org = await prisma.organizations.findFirst({
      where: { id: organizationId },
      select: {
        id: true,
        ownerId: true,
        greetingMessageEn: true,
        greetingMessageAr: true,
        autoGreetingEnabled: true,
      },
    });

    if (!org) {
      return NextResponse.json(
        { success: false, error: "Organization not found" },
        { status: 404 },
      );
    }

    if (org.ownerId !== user.userId) {
      return NextResponse.json(
        { success: false, error: "Forbidden" },
        { status: 403 },
      );
    }

    return NextResponse.json({
      success: true,
      greetingMessageEn: org.greetingMessageEn ?? null,
      greetingMessageAr: org.greetingMessageAr ?? null,
      autoGreetingEnabled: org.autoGreetingEnabled ?? true,
    });
  } catch (error) {
    scopedLogger.error("Failed to load WhatsApp greeting", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

// =============================================================================
// PATCH — update greeting
// =============================================================================

export async function PATCH(request: NextRequest) {
  try {
    const rateLimitResponse = await applyRateLimit(
      request,
      rateLimiters.authGeneral,
    );
    if (rateLimitResponse) return rateLimitResponse;

    if (!validateCSRFToken(request)) {
      return NextResponse.json(
        { success: false, error: "Invalid CSRF token" },
        { status: 403 },
      );
    }

    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const rawBody = (await request.json().catch(() => null)) as unknown;
    const parsed = patchSchema.safeParse(rawBody);
    if (!parsed.success) {
      return NextResponse.json(
        {
          success: false,
          error: "Invalid request body",
          details: parsed.error.flatten(),
        },
        { status: 400 },
      );
    }

    const {
      organizationId,
      greetingMessageEn,
      greetingMessageAr,
      autoGreetingEnabled,
    } = parsed.data;

    // Verify the authenticated user owns this org
    const org = await prisma.organizations.findFirst({
      where: { id: organizationId },
      select: { id: true, ownerId: true },
    });

    if (!org) {
      return NextResponse.json(
        { success: false, error: "Organization not found" },
        { status: 404 },
      );
    }

    if (org.ownerId !== user.userId) {
      return NextResponse.json(
        { success: false, error: "Forbidden" },
        { status: 403 },
      );
    }

    // Build the patch payload — only forward fields the client actually sent
    const patch: Record<string, unknown> = { organizationId };
    if (greetingMessageEn !== undefined) {
      patch.greetingMessageEn =
        typeof greetingMessageEn === "string"
          ? greetingMessageEn.trim()
          : greetingMessageEn;
    }
    if (greetingMessageAr !== undefined) {
      patch.greetingMessageAr =
        typeof greetingMessageAr === "string"
          ? greetingMessageAr.trim()
          : greetingMessageAr;
    }
    if (autoGreetingEnabled !== undefined) {
      patch.autoGreetingEnabled = autoGreetingEnabled;
    }

    await convexMutation(
      "organizations/mutations:updateOrganizationNoAuth",
      patch,
    );

    scopedLogger.info("WhatsApp greeting updated", {
      organizationId,
      hasEn: greetingMessageEn !== undefined,
      hasAr: greetingMessageAr !== undefined,
      hasEnabled: autoGreetingEnabled !== undefined,
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    scopedLogger.error("Failed to update WhatsApp greeting", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
