import { PrismaClient } from "@prisma/client";

const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined;
  migrated?: boolean;
};

export const prisma =
  globalForPrisma.prisma ??
  new PrismaClient({
    log: process.env.NODE_ENV === "development" ? ["warn", "error"] : ["error"],
  });

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;

// Auto-healing migration & High-Performance SQLite Tuning
const isBuild = process.env.NEXT_PHASE === "phase-production-build" || process.env.npm_lifecycle_event === "build";
if (!globalForPrisma.migrated && !isBuild) {
  globalForPrisma.migrated = true;
  (async () => {
    try {
      // ⚡ 1. SQLite Engine Performance Boosters
      await prisma.$queryRawUnsafe(`PRAGMA journal_mode = WAL;`).catch(() => {});
      await prisma.$queryRawUnsafe(`PRAGMA synchronous = NORMAL;`).catch(() => {});
      await prisma.$queryRawUnsafe(`PRAGMA busy_timeout = 30000;`).catch(() => {});
      await prisma.$queryRawUnsafe(`PRAGMA cache_size = -64000;`).catch(() => {});
      await prisma.$queryRawUnsafe(`PRAGMA temp_store = MEMORY;`).catch(() => {});
      await prisma.$queryRawUnsafe(`PRAGMA mmap_size = 268435456;`).catch(() => {});

      // ⚡ 2. Essential tables if not exists
      
      await prisma.$executeRawUnsafe(`CREATE TABLE IF NOT EXISTS "Report" (
        "id" TEXT PRIMARY KEY,
        "mediaId" TEXT,
        "reporterIp" TEXT,
        "reason" TEXT,
        "comment" TEXT,
        "status" TEXT DEFAULT 'PENDING',
        "createdAt" DATETIME DEFAULT CURRENT_TIMESTAMP
      );`).catch(() => {});
      
      await prisma.$executeRawUnsafe(`CREATE TABLE IF NOT EXISTS "BannedHash" (
        "hash" TEXT PRIMARY KEY,
        "reason" TEXT,
        "bannedAt" DATETIME DEFAULT CURRENT_TIMESTAMP
      );`).catch(() => {});

      // ⚡ 3. High Performance Query Indexes (< 1ms queries)
      await prisma.$executeRawUnsafe(`CREATE INDEX IF NOT EXISTS idx_media_pub_created ON "Media" ("isPublished", "type", "createdAt" DESC);`).catch(() => {});
      await prisma.$executeRawUnsafe(`CREATE INDEX IF NOT EXISTS idx_media_pub_views ON "Media" ("isPublished", "type", "views" DESC);`).catch(() => {});
      await prisma.$executeRawUnsafe(`CREATE INDEX IF NOT EXISTS idx_media_format ON "Media" ("format", "isPublished", "createdAt" DESC);`).catch(() => {});
      await prisma.$executeRawUnsafe(`CREATE INDEX IF NOT EXISTS idx_media_category ON "Media" ("categoryId", "isPublished");`).catch(() => {});
      await prisma.$executeRawUnsafe(`CREATE INDEX IF NOT EXISTS idx_media_cat_pub_views ON "Media" ("categoryId", "isPublished", "type", "views" DESC);`).catch(() => {});
      await prisma.$executeRawUnsafe(`CREATE INDEX IF NOT EXISTS idx_media_cat_pub_created ON "Media" ("categoryId", "isPublished", "type", "createdAt" DESC);`).catch(() => {});
      await prisma.$executeRawUnsafe(`CREATE INDEX IF NOT EXISTS idx_sitesetting_key ON "SiteSetting" ("key");`).catch(() => {});

    } catch (err) {
      console.error("Auto-sync SQLite error:", err);
    }
  })();
}
