// app/api/install/test-db/route.ts
import { NextRequest, NextResponse } from "next/server";
import { PrismaClient } from "@prisma/client";
import { isInstalled } from "@/lib/install-state";
import { validateDbConnectionInput, buildMysqlUrl } from "@/lib/db-connection";

export async function POST(req: NextRequest) {
  // Defense in depth: even though middleware already blocks this route
  // once installed, the route itself refuses too.
  if (isInstalled()) {
    return NextResponse.json({ error: "Already installed" }, { status: 409 });
  }

  const body = await req.json().catch(() => null);
  if (!body) {
    return NextResponse.json({ error: "Invalid request body" }, { status: 400 });
  }

  const validation = validateDbConnectionInput(body);
  if (!validation.valid) {
    return NextResponse.json({ error: validation.error }, { status: 422 });
  }

  const url = buildMysqlUrl(body);

  // A short-lived Prisma client pointed at the candidate connection string —
  // completely separate from the app's real singleton in lib/prisma.ts,
  // which still points at DATABASE_URL (or its placeholder) the whole time.
  const testClient = new PrismaClient({ datasourceUrl: url });

  try {
    await testClient.$queryRaw`SELECT 1`;
    return NextResponse.json({ ok: true });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Unknown connection error";
    // Trim overly technical Prisma error text down to something readable.
    const friendly = message.split("\n")[0].slice(0, 300);
    return NextResponse.json({ ok: false, error: friendly }, { status: 200 });
  } finally {
    await testClient.$disconnect().catch(() => {
      /* already logged via the outer catch if this mattered */
    });
  }
}
