/**
 * Widget Settings API
 * GET - Get review widget settings
 * PUT - Create or update widget settings
 *
 * All data via Convex. No Prisma.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveDataOwnerId } from "@/lib/utils/organization-data";
import { logger } from "@/lib/logger";
import { convexQuery, convexMutation } from "@/lib/convex-client";

const log = logger.scope("WidgetSettingsAPI");

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

    const ownerResult = await getEffectiveDataOwnerId(user.userId);
    const effectiveUserId = ownerResult.effectiveUserId;
    const settings = await convexQuery<{ businessName?: string } | null>("reviews/queries:getWidgetSettings", {
      userId: effectiveUserId,
    });

    // Resolve the org's canonical business name for the client to use as default
    let defaultBusinessName: string | undefined;
    try {
      const companyName = await convexQuery<string | null>(
        "auth/queries:getCompanyNameByAppUserId",
        { appUserId: effectiveUserId },
      );
      if (companyName) {
        defaultBusinessName = companyName;
      }
    } catch {
      // Non-critical
    }
    if (!defaultBusinessName && ownerResult.organizationName) {
      defaultBusinessName = ownerResult.organizationName;
    }

    // Override businessName in returned settings with canonical company name
    const resolvedSettings = settings
      ? { ...settings, businessName: defaultBusinessName || settings.businessName }
      : null;

    return NextResponse.json({
      success: true,
      settings: resolvedSettings,
      ...(defaultBusinessName ? { defaultBusinessName } : {}),
    });
  } catch (error) {
    log.error("Failed to get widget settings", {
      error: error instanceof Error ? error.message : String(error),
    });
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

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

    const { effectiveUserId } = await getEffectiveDataOwnerId(user.userId);
    const body = await request.json();

    // Always use the canonical company name from Convex
    let companyName: string | undefined;
    try {
      const name = await convexQuery<string | null>(
        "auth/queries:getCompanyNameByAppUserId",
        { appUserId: effectiveUserId },
      );
      if (name) companyName = name;
    } catch {
      // Non-critical
    }

    await convexMutation("reviews/mutations:updateWidgetSettings", {
      userId: effectiveUserId,
      ...body,
      ...(companyName ? { businessName: companyName } : {}),
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    log.error("Failed to update widget settings", {
      error: error instanceof Error ? error.message : String(error),
    });
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
