import type { SavedConnection } from '../types';

export type DriverStatusSnapshot = {
  type: string;
  name: string;
  connectable: boolean;
  expectedRevision?: string;
  needsUpdate?: boolean;
  updateReason?: string;
  affectedConnections?: number;
  message?: string;
};

export const normalizeDriverType = (value: string): string => {
  const normalized = String(value || '').trim().toLowerCase();
  if (normalized === 'postgresql' || normalized === 'pg' || normalized === 'pq' || normalized === 'pgx') return 'postgres';
  if (normalized === 'elastic') return 'elasticsearch';
  if (normalized === 'doris') return 'diros';
  if (
    normalized === 'open_gauss' ||
    normalized === 'open-gauss' ||
    normalized === 'opengauss'
  ) return 'opengauss';
  if (
    normalized === 'intersystems' ||
    normalized === 'intersystemsiris' ||
    normalized === 'inter-systems' ||
    normalized === 'inter-systems-iris'
  ) return 'iris';
  return normalized;
};

export const resolveConnectionDriverType = (type: string, driver?: string): string => {
  const normalizedType = normalizeDriverType(type);
  if (normalizedType !== 'custom') {
    return normalizedType;
  }
  return normalizeDriverType(driver || '');
};

export const resolveSavedConnectionDriverType = (conn: SavedConnection | undefined): string => {
  return resolveConnectionDriverType(conn?.config?.type || '', conn?.config?.driver || '');
};

export const isPostgresSchemaDialect = (dialect: string): boolean => (
  ['postgres', 'kingbase', 'highgo', 'vastbase', 'opengauss'].includes(normalizeDriverType(dialect))
);
