// lib/prisma.ts

import "dotenv/config";
import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3";
import { PrismaClient } from "../generated/prisma/client";

const isProd = process.env.NODE_ENV === "production";
const defaultUrl = isProd ? "file:/app/data/kullaberg.db" : "file:./prisma/dev.db";
const dbUrl = process.env.DATABASE_URL || defaultUrl;
const adapter = new PrismaBetterSqlite3({
    url: dbUrl
});

const prismaClientSingleton = () => {
    return new PrismaClient({ adapter });
};

declare global {
    var prismaGlobal: undefined | ReturnType<typeof prismaClientSingleton>;
}

const prisma = globalThis.prismaGlobal ?? prismaClientSingleton();

export default prisma;

if (!isProd) {
    globalThis.prismaGlobal = prisma;
}