import { createHash, randomBytes, randomUUID } from "node:crypto";
import { NextResponse } from "next/server";
import { getDbPool } from "@/db";
import { getSession } from "@/lib/auth";

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

const directions = new Set(["inbound", "outbound"]);
const authTypes = new Set(["none", "bearer", "api_key"]);
const hashKey = (value: string) => createHash("sha256").update(value).digest("hex");

async function admin() {
  const session = await getSession();
  return session?.role === "capital_admin" ? session : null;
}

export async function GET() {
  const session = await admin();
  if (!session) return NextResponse.json({ error: "Somente administradores da Capital podem configurar integrações." }, { status: 403 });
  try {
    const db = getDbPool();
    const [tenants] = await db.execute("SELECT id, name, slug FROM tenants WHERE status = 'active' ORDER BY name");
    const [connections] = await db.execute(
      `SELECT c.id, c.tenant_id, t.name AS tenant_name, c.name, c.direction, c.status, c.endpoint_url, c.auth_type, c.credential_reference, c.created_at, c.updated_at,
              (SELECT COUNT(*) FROM integration_delivery_logs l WHERE l.integration_connection_id = c.id) AS deliveries
       FROM integration_connections c INNER JOIN tenants t ON t.id = c.tenant_id ORDER BY c.updated_at DESC`,
    );
    return NextResponse.json({ tenants, connections });
  } catch (error) {
    console.error("Erro ao carregar integrações", error);
    return NextResponse.json({ error: "A estrutura de integrações ainda não foi instalada.", hint: "Execute a migration 012_integrations.sql." }, { status: 503 });
  }
}

export async function POST(request: Request) {
  const session = await admin();
  if (!session) return NextResponse.json({ error: "Somente administradores da Capital podem configurar integrações." }, { status: 403 });
  try {
    const body = await request.json();
    if (body.action === "regenerate") {
      const connectionId = String(body.connectionId || "");
      if (!connectionId) return NextResponse.json({ error: "Informe a conexão de entrada." }, { status: 400 });
      const db = getDbPool();
      const [rows] = await db.execute("SELECT id FROM integration_connections WHERE id = ? AND direction = 'inbound' LIMIT 1", [connectionId]);
      if (!(rows as unknown[]).length) return NextResponse.json({ error: "Conexão de entrada não encontrada." }, { status: 404 });
      const apiKey = `cav_${randomBytes(30).toString("base64url")}`;
      await db.execute("UPDATE integration_connections SET api_key_hash = ?, updated_at = NOW() WHERE id = ?", [hashKey(apiKey), connectionId]);
      return NextResponse.json({ message: "Nova chave criada. A chave anterior foi revogada imediatamente.", apiKey, inboundEndpoint: "/api/public/v1/inspections" });
    }
    const tenantId = String(body.tenantId || "");
    const name = String(body.name || "").trim().slice(0, 160);
    const direction = String(body.direction || "");
    const endpointUrl = String(body.endpointUrl || "").trim().slice(0, 500);
    const authType = String(body.authType || "api_key");
    const credentialReference = String(body.credentialReference || "").trim().slice(0, 160);
    if (!tenantId || !name || !directions.has(direction) || !authTypes.has(authType)) return NextResponse.json({ error: "Informe cliente, nome, direção e autenticação." }, { status: 400 });
    if (direction === "outbound" && !endpointUrl) return NextResponse.json({ error: "Informe a URL de destino para uma integração de saída." }, { status: 400 });
    if (endpointUrl && !/^https:\/\//i.test(endpointUrl)) return NextResponse.json({ error: "Por segurança, a URL da integração deve usar HTTPS." }, { status: 400 });

    const apiKey = direction === "inbound" ? `cav_${randomBytes(30).toString("base64url")}` : null;
    await getDbPool().execute(
      "INSERT INTO integration_connections (id, tenant_id, name, direction, endpoint_url, auth_type, credential_reference, api_key_hash, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
      [randomUUID(), tenantId, name, direction, endpointUrl || null, authType, credentialReference || null, apiKey ? hashKey(apiKey) : null, session.name],
    );
    return NextResponse.json({ message: "Integração cadastrada.", apiKey, inboundEndpoint: apiKey ? "/api/public/v1/inspections" : null }, { status: 201 });
  } catch (error: unknown) {
    console.error("Erro ao cadastrar integração", error);
    const code = typeof error === "object" && error && "code" in error ? String(error.code) : "";
    if (code === "ER_NO_REFERENCED_ROW_2") return NextResponse.json({ error: "Cliente não encontrado." }, { status: 404 });
    return NextResponse.json({ error: "Não foi possível cadastrar a integração.", hint: "Verifique se a migration 012 foi executada." }, { status: 500 });
  }
}
