import { PrismaClient } from "@prisma/client";
import { PrismaMariaDb } from "@prisma/adapter-mariadb";

// Prisma 7 removed the Rust query engine; the runtime DB connection is now made
// through a driver adapter. PrismaMariaDb wraps the `mariadb` driver (which is
// MySQL-wire compatible). We parse DATABASE_URL ourselves and pass an explicit
// pool config rather than the raw connection string, so a literal `@` in the
// password (which a naive connection-string parser would mishandle) is handled
// correctly.
function mariadbAdapterFromUrl(rawUrl: string): PrismaMariaDb {
  const u = new URL(rawUrl);
  return new PrismaMariaDb({
    host: u.hostname,
    port: u.port ? Number(u.port) : 3306,
    user: decodeURIComponent(u.username),
    password: decodeURIComponent(u.password),
    database: u.pathname.replace(/^\//, ""),
  });
}

const adapter = mariadbAdapterFromUrl(process.env.DATABASE_URL as string);

const prisma = new PrismaClient({
  adapter,
  log: process.env.APP_ENV === "local" ? ["warn", "error"] : ["error"],
});

export default prisma;
