/**
 * Appointment Types Auto-Translate API
 *
 * POST /api/dashboard/appointment-types/translate
 *   Translates an English service/product name to Qatari Arabic dialect using
 *   the shared qatariDialectService (Anthropic claude-haiku + LRU cache).
 *
 * Request body:
 *   { text: string }
 *
 * Response (success):
 *   { success: true, translation: string }
 *
 * Response (error):
 *   { success: false, error: string }
 *
 * Note: The frontend checks for `data.success && data.translation`.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { logger } from "@/lib/logger";
import { withCSRF } from "@/lib/csrf";
import { withRateLimit, rateLimiters } from "@/lib/rate-limiter";
import { qatariDialectService } from "@/lib/services/qatari-dialect.service";

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

export const dynamic = "force-dynamic";

async function postHandler(request: NextRequest): Promise<NextResponse> {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    let body: unknown;
    try {
      body = await request.json();
    } catch {
      return NextResponse.json(
        { success: false, error: "Invalid JSON body" },
        { status: 400 },
      );
    }

    const { text } = body as { text?: unknown };

    if (!text || String(text).trim().length === 0) {
      return NextResponse.json(
        { success: false, error: "text is required" },
        { status: 400 },
      );
    }

    const inputText = String(text).trim();

    if (inputText.length > 500) {
      return NextResponse.json(
        { success: false, error: "text must be 500 characters or fewer" },
        { status: 400 },
      );
    }

    const result = await qatariDialectService.translateToQatari(inputText);

    if (!result.translation) {
      scopedLogger.warn("Translation returned empty result", {
        userId: user.userId,
        inputText,
        source: result.source,
      });
      return NextResponse.json(
        { success: false, error: "Translation failed" },
        { status: 502 },
      );
    }

    scopedLogger.info("Text translated to Qatari Arabic", {
      userId: user.userId,
      source: result.source,
      cached: result.cached,
    });

    return NextResponse.json({
      success: true,
      translation: result.translation,
      source: result.source,
    });
  } catch (error) {
    scopedLogger.error("Failed to translate text", error);
    return NextResponse.json(
      { success: false, error: "Translation service unavailable" },
      { status: 502 },
    );
  }
}

export const POST = withRateLimit(
  withCSRF(postHandler),
  rateLimiters.authGeneral,
);
