import { NextResponse } from "next/server";
import { resolveRequestTenant } from "@/core/tenant/request-tenant";
import { createInquiry } from "@/services/inquiry-service";
import { createInquirySchema } from "@/core/validation/schemas";

/**
 * Public inquiry submission.
 * tenant_id from body is ignored — trusted TenantContext wins.
 */
export async function POST(request: Request) {
  const resolved = await resolveRequestTenant();
  if (!resolved.ok) {
    return NextResponse.json({ error: "Tenant not available" }, { status: 404 });
  }

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

  // Strip any client-supplied tenant identifiers before validation
  if (body && typeof body === "object") {
    const unsafe = body as Record<string, unknown>;
    delete unsafe.tenant_id;
    delete unsafe.tenantId;
  }

  const parsed = createInquirySchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { error: "Validation failed", details: parsed.error.flatten() },
      { status: 400 },
    );
  }

  try {
    const inquiry = await createInquiry(resolved.context, parsed.data);
    return NextResponse.json({ id: inquiry?.id }, { status: 201 });
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Unable to create inquiry";
    console.error("Inquiry create failed", error);
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
