import { PrismaClient } from '@prisma/client';
import { PrismaD1 } from '@prisma/adapter-d1';

// For local development fallback
const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined;
};

/**
 * Get Prisma client for Cloudflare Workers with D1.
 * This should be called in each request handler to get a fresh client with D1 binding.
 */
export function getPrismaWithD1(): PrismaClient {
  // Try to get Cloudflare context (only works in Workers environment)
  try {
    // eslint-disable-next-line @typescript-eslint/no-require-imports
    const { getCloudflareContext } = require('@opennextjs/cloudflare');
    const ctx = getCloudflareContext();

    if (ctx?.env?.DB) {
      const adapter = new PrismaD1(ctx.env.DB);
      return new PrismaClient({ adapter });
    }
  } catch (error) {
    console.error('[getPrismaWithD1] Failed to get Cloudflare context:', error);
    // Not in Cloudflare Workers environment, fall back to local client
  }

  // Fallback for local development
  if (!globalForPrisma.prisma) {
    globalForPrisma.prisma = new PrismaClient();
  }

  return globalForPrisma.prisma;
}

// Legacy synchronous export for backward compatibility in local dev
// NOTE: This does NOT work with D1 in production - use getPrismaWithD1() instead
export const prisma = globalForPrisma.prisma ?? new PrismaClient();

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