import { PrismaClient } from '@prisma/client';
import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3';

// Ensure env vars are loaded
import 'dotenv/config';

declare global {
  // allow global `var` declarations
  // eslint-disable-next-line no-var
  var prisma: PrismaClient | undefined;
}

const mode = process.env.APP_MODE || 'dev';
console.log(`[Prisma] Initializing in ${mode.toUpperCase()} mode`);

let dbUrl: string | undefined;

switch (mode) {
  case 'test':
    dbUrl = process.env.DATABASE_URL_TEST;
    break;
  case 'prod':
    dbUrl = process.env.DATABASE_URL_PROD;
    break;
  case 'dev':
  default:
    dbUrl = process.env.DATABASE_URL_DEV;
    break;
}

// Fallback to generic DATABASE_URL if specific one is missing
if (!dbUrl) {
  console.warn(`[Prisma] DATABASE_URL_${mode.toUpperCase()} not found, falling back to DATABASE_URL`);
  dbUrl = process.env.DATABASE_URL;
}

if (!dbUrl) {
  throw new Error(`DATABASE_URL environment variable is not set for mode ${mode}. Please check your .env file.`);
}

console.log('Initializing Prisma Adapter with URL:', dbUrl);

// Use the options object as required by the library definitions
const adapter = new PrismaBetterSqlite3({ url: dbUrl });

const prisma =
  global.prisma ||
  new PrismaClient({
    adapter,
  });

if (process.env.NODE_ENV !== 'production') {
  global.prisma = prisma;
}

export default prisma;
