import "server-only";

import { sql } from "drizzle-orm";
import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js";
import postgres from "postgres";

import * as schema from "@/modules/core/server/schema";

export type AppDatabase = PostgresJsDatabase<typeof schema>;

let cachedDatabase: AppDatabase | null = null;
let cachedClient: postgres.Sql | null = null;

export function getDatabase(): AppDatabase {
  const databaseUrl = process.env.DATABASE_URL;
  if (!databaseUrl) {
    throw new Error("DATABASE_URL is required for database-backed system configuration");
  }

  if (!cachedDatabase) {
    cachedClient = postgres(databaseUrl, { max: 1 });
    cachedDatabase = drizzle(cachedClient, { schema });
  }

  return cachedDatabase;
}

export async function checkDatabaseConnection(): Promise<{ ok: boolean; reason: string }> {
  try {
    const database = getDatabase();
    await database.execute(sql`select 1`);
    return { ok: true, reason: "数据库连接正常" };
  } catch (error) {
    const reason = error instanceof Error ? error.message : "数据库连接失败";
    return { ok: false, reason };
  }
}
