export type ServerConfig = {
  uploadMaxMB: number;
  uploadDir: string;
  dbHost: string;
  dbPort: string;
  dbUser: string;
  dbPass: string;
  dbName: string;
};

function parseDbFromEnv(): { host: string; port: string; user: string; pass: string; name: string } {
  const url = process.env.DATABASE_URL || '';
  try {
    if (url) {
      const u = new URL(url);
      const host = u.hostname || '127.0.0.1';
      const port = u.port || '3306';
      const user = decodeURIComponent(u.username || 'root');
      const pass = decodeURIComponent(u.password || '');
      const name = (u.pathname || '/nexus_db').replace(/^\//, '') || 'nexus_db';
      return { host, port, user, pass, name };
    }
  } catch {}
  const host = process.env.DB_HOST || '127.0.0.1';
  const port = process.env.DB_PORT || '3306';
  const user = process.env.DB_USER || 'root';
  const pass = process.env.DB_PASSWORD || '';
  const name = process.env.DB_NAME || 'nexus_db';
  return { host, port, user, pass, name };
}

const dbEnv = parseDbFromEnv();

const config: ServerConfig = {
  uploadMaxMB: parseInt(process.env.MAX_UPLOAD_MB || '') || 3,
  uploadDir: process.env.UPLOAD_DIR || 'data',
  dbHost: dbEnv.host,
  dbPort: dbEnv.port,
  dbUser: dbEnv.user,
  dbPass: dbEnv.pass,
  dbName: dbEnv.name,
};

export const getServerConfig = () => config;
export const setServerConfig = (next: Partial<ServerConfig>) => {
  if (typeof next.uploadMaxMB === 'number') config.uploadMaxMB = next.uploadMaxMB;
  if (typeof next.uploadDir === 'string' && next.uploadDir.trim()) config.uploadDir = next.uploadDir.trim();
  if (typeof next.dbHost === 'string') config.dbHost = next.dbHost;
  if (typeof next.dbPort === 'string') config.dbPort = next.dbPort;
  if (typeof next.dbUser === 'string') config.dbUser = next.dbUser;
  if (typeof next.dbPass === 'string') config.dbPass = next.dbPass;
  if (typeof next.dbName === 'string') config.dbName = next.dbName;
  return config;
};
