import { NextResponse } from "next/server";

type LeadRequestBody = {
  name?: string;
  phone?: string;
  email?: string | null;
  message?: string | null;
};

function normalizePhone(input: string) {
  const digits = input.replace(/\D/g, "");

  if (digits.length === 11 && (digits.startsWith("7") || digits.startsWith("8"))) {
    return `+7${digits.slice(1)}`;
  }

  if (digits.length === 10) {
    return `+7${digits}`;
  }

  return null;
}

export async function POST(request: Request) {
  const apiUrl = process.env.ESPOCRM_API_URL?.trim();
  const apiKey = process.env.ESPOCRM_API_KEY?.trim();
  const leadSource = process.env.ESPOCRM_LEAD_SOURCE?.trim() || "Web Site";

  if (!apiUrl || !apiKey) {
    console.error("EspoCRM env is not configured");
    return NextResponse.json(
      { error: "Интеграция CRM временно не настроена" },
      { status: 500 },
    );
  }

  try {
    const body = (await request.json()) as LeadRequestBody;
    const name = body.name?.trim() || "";
    const email = body.email?.trim() || null;
    const message = body.message?.trim() || null;
    const phoneNumber = body.phone ? normalizePhone(body.phone) : null;

    if (name.length < 2 || !phoneNumber) {
      return NextResponse.json(
        { error: "Проверьте название объекта и номер телефона" },
        { status: 400 },
      );
    }

    const descriptionParts = [`Объект/компания: ${name}`];

    if (message) {
      descriptionParts.push(message);
    } else {
      descriptionParts.push("Заявка с сайта");
    }

    if (email) {
      descriptionParts.push(`Email: ${email}`);
    }

    const payload = {
      name,
      accountName: name,
      phoneNumber,
      emailAddress: email,
      description: descriptionParts.join("\n"),
      source: leadSource,
    };

    const response = await fetch(apiUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
        "X-Api-Key": apiKey,
      },
      body: JSON.stringify(payload),
      cache: "no-store",
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error("EspoCRM lead create failed:", response.status, errorText);

      return NextResponse.json(
        { error: "Не удалось отправить заявку в CRM" },
        { status: 502 },
      );
    }

    return NextResponse.json({ success: true }, { status: 201 });
  } catch (error) {
    console.error("POST /api/leads error:", error);
    return NextResponse.json(
      { error: "Не удалось обработать заявку" },
      { status: 500 },
    );
  }
}
