import { createHash, randomBytes, randomUUID } from "node:crypto";
import { NextResponse } from "next/server";
import { getDbPool } from "@/db";
import { sendInspectionWhatsApp } from "@/lib/twilio-whatsapp";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const vehicleTypes = new Set(["light", "motorcycle", "heavy"]);
const deliveryChannels = new Set(["whatsapp", "sms", "email"]);
const keyHash = (value: string) => createHash("sha256").update(value).digest("hex");
const text = (value: unknown) => typeof value === "string" ? value.trim() : "";

function apiKey(request: Request) {
  const bearer = request.headers.get("authorization")?.match(/^Bearer\s+(.+)$/i)?.[1];
  return bearer || request.headers.get("x-api-key") || "";
}

export async function POST(request: Request) {
  const providedKey = apiKey(request);
  if (!providedKey) return NextResponse.json({ error: "Informe a chave da API em Authorization: Bearer <chave> ou X-API-Key." }, { status: 401 });
  try {
    const db = getDbPool();
    const [connectionRows] = await db.execute(
      "SELECT id, tenant_id FROM integration_connections WHERE direction = 'inbound' AND status = 'active' AND api_key_hash = ? LIMIT 1",
      [keyHash(providedKey)],
    );
    const connection = (connectionRows as { id: string; tenant_id: string }[])[0];
    if (!connection) return NextResponse.json({ error: "Chave de integração inválida ou inativa." }, { status: 401 });

    const body = await request.json();
    const externalId = text(body.externalId || body.proposal);
    const vehicleType = text(body.vehicleType || body.vehicle_type);
    const plate = text(body.plate).toUpperCase();
    const chassis = text(body.chassis).toUpperCase();
    const vehicleDescription = text(body.vehicleDescription || body.vehicle_description);
    const responsibleName = text(body.responsibleName || body.responsible_name);
    const responsiblePhone = text(body.responsiblePhone || body.responsible_phone);
    const responsibleEmail = text(body.responsibleEmail || body.responsible_email).toLowerCase();
    const deliveryChannel = text(body.deliveryChannel || body.delivery_channel).toLowerCase() || "whatsapp";
    const yearRaw = Number.parseInt(text(body.modelYear || body.model_year), 10);
    if (!externalId || !vehicleTypes.has(vehicleType) || !plate || !responsibleName || !responsiblePhone) return NextResponse.json({ error: "Campos obrigatórios: externalId, vehicleType, plate, responsibleName e responsiblePhone." }, { status: 400 });
    if (!deliveryChannels.has(deliveryChannel)) return NextResponse.json({ error: "deliveryChannel deve ser whatsapp, sms ou email." }, { status: 400 });
    if (deliveryChannel === "email" && !responsibleEmail) return NextResponse.json({ error: "Informe responsibleEmail quando o canal de entrega for e-mail." }, { status: 400 });

    const id = randomUUID();
    await db.execute(
      "INSERT INTO inspections (id, tenant_id, external_id, vehicle_type, plate, chassis, vehicle_description, model_year, responsible_name, responsible_phone, responsible_email, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'received')",
      [id, connection.tenant_id, externalId, vehicleType, plate, chassis, vehicleDescription || null, Number.isNaN(yearRaw) ? null : yearRaw, responsibleName, responsiblePhone, responsibleEmail || null],
    );
    const token = randomBytes(32).toString("base64url");
    const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
    await db.execute(
      "INSERT INTO inspection_access_links (id, inspection_id, inspection_cycle, token, expires_at) VALUES (?, ?, 1, ?, ?)",
      [randomUUID(), id, token, expiresAt],
    );
    await db.execute("UPDATE inspections SET status = 'link_sent' WHERE id = ?", [id]);
    const requestId = request.headers.get("x-request-id") || randomUUID();
    await db.execute(
      "INSERT INTO integration_delivery_logs (id, integration_connection_id, inspection_id, direction, event_type, status, request_id, http_status, summary) VALUES (?, ?, ?, 'inbound', 'inspection.created', 'received', ?, 201, ?)",
      [randomUUID(), connection.id, id, requestId, `Solicitação ${externalId} recebida via API; link seguro gerado para envio por ${deliveryChannel}.`],
    );
    const inspectionPath = `/vistoria/${token}`;
    const inspectionUrl = new URL(inspectionPath, request.url).toString();
    const delivery = deliveryChannel === "whatsapp"
      ? await sendInspectionWhatsApp({ inspectionId: id, tenantId: connection.tenant_id, responsibleName: responsibleName || null, responsiblePhone: responsiblePhone || null, inspectionUrl })
      : { status: "awaiting_provider" as const, message: `Link gerado. O canal ${deliveryChannel} será disponibilizado quando o respectivo broker estiver configurado.` };
    return NextResponse.json({ id, externalId, status: "link_sent", inspectionPath, expiresAt, delivery: { channel: deliveryChannel, ...delivery }, message: "Solicitação recebida e link de vistoria gerado com sucesso." }, { status: 201, headers: { "X-Request-Id": requestId } });
  } catch (error: unknown) {
    const code = typeof error === "object" && error && "code" in error ? String(error.code) : "";
    if (code === "ER_DUP_ENTRY") return NextResponse.json({ error: "Já existe uma vistoria com este identificador para este cliente." }, { status: 409 });
    console.error("Erro na API pública de vistorias", error);
    return NextResponse.json({ error: "Não foi possível registrar a solicitação.", hint: "Verifique a estrutura da API e o identificador enviado." }, { status: 500 });
  }
}
