import { localDataSource } from './LocalDataSource';
import { databaseManager } from './core/DatabaseManager';

export { databaseManager } from './core/DatabaseManager';
export { DatabaseManager } from './core/DatabaseManager';
export { localDataSource, LocalDataSource } from './LocalDataSource';

export {
  messageRepository, MessageRepository,
  conversationRepository, ConversationRepository,
  userCacheRepository, UserCacheRepository,
  groupCacheRepository, GroupCacheRepository,
  postCacheRepository, PostCacheRepository,
} from './repositories';

export { CachedMessage } from './types';

export async function clearAllData(): Promise<void> {
  await localDataSource.enqueueWrite(async () => {
    await localDataSource.execute(`DELETE FROM messages`);
    await localDataSource.execute(`DELETE FROM conversations`);
    await localDataSource.execute(`DELETE FROM conversation_cache`);
    await localDataSource.execute(`DELETE FROM conversation_list_cache`);
    await localDataSource.execute(`DELETE FROM users`);
    await localDataSource.execute(`DELETE FROM current_user_cache`);
    await localDataSource.execute(`DELETE FROM groups`);
    await localDataSource.execute(`DELETE FROM group_members`);
    await localDataSource.execute(`DELETE FROM posts_cache`);
  });
}

export const initDatabase = async (userId?: string | null): Promise<void> => {
  await databaseManager.initialize(userId);
};

export const switchDatabase = async (userId?: string | null): Promise<void> => {
  await localDataSource.switchDatabase(userId);
};

export const closeDatabase = async (): Promise<void> => {
  await localDataSource.closeDatabase();
};

export const getCurrentDbUserId = (): string | null => {
  return databaseManager.getCurrentUserId();
};

export const isDbInitialized = (): boolean => {
  return databaseManager.isReady();
};

export const getDbInstance = () => {
  return databaseManager.getDbSync();
};

export const getDb = async () => {
  return databaseManager.getDb();
};