import { PrismaClient } from '@prisma/client';
import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3';
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 dbPath: string;

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

// Remove 'file:' prefix if present
if (dbPath.startsWith('file:')) {
  dbPath = dbPath.slice(5);
}

console.log('Initializing Prisma Client with database:', dbPath);

let prisma: PrismaClient;

try {
  const adapter = new PrismaBetterSqlite3({ url: dbPath });

  prisma =
    global.prisma ||
    new PrismaClient({
      adapter: adapter as any,
    });
} catch (e: any) {
  console.error('Failed to initialize Prisma Client:', e.message);
  process.exit(1);
}

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

export default prisma;

