# DatabaseUtil to PlatformServiceMixin Migration Plan

## Migration Overview

This plan migrates database utility functions from `src/db/databaseUtil.ts` to `src/utils/PlatformServiceMixin.ts` to consolidate database operations and reduce boilerplate code across the application.

## Priority Levels

### 🔴 **PRIORITY 1 (Critical - Migrate First)**

Functions used in 50+ files that are core to application functionality

### 🟡 **PRIORITY 2 (High - Migrate Second)**

Functions used in 10-50 files that are important but not critical

### 🟢 **PRIORITY 3 (Medium - Migrate Third)**

Functions used in 5-10 files that provide utility but aren't frequently used

### 🔵 **PRIORITY 4 (Low - Migrate Last)**

Functions used in <5 files or specialized functions

## Detailed Migration Plan

### 🔴 **PRIORITY 1 - Critical Functions**

#### 1. `retrieveSettingsForActiveAccount()`

- **Usage**: 60+ files
- **Current**: `databaseUtil.retrieveSettingsForActiveAccount()`
- **Target**: `this.$settings()` (already exists in PlatformServiceMixin)
- **Migration**: Replace all calls with `this.$settings()`
- **Files to migrate**: All view files, components, and services

#### 2. `logConsoleAndDb()` and `logToDb()`

- **Usage**: 40+ files
- **Current**: `databaseUtil.logConsoleAndDb()` / `databaseUtil.logToDb()`
- **Target**: Add `$log()` and `$logError()` methods to PlatformServiceMixin
- **Migration**: Replace with `this.$log()` and `this.$logError()`
- **Files to migrate**: All error handling and logging code

#### 3. `mapQueryResultToValues()` and `mapColumnsToValues()`

- **Usage**: 30+ files
- **Current**: `databaseUtil.mapQueryResultToValues()` / `databaseUtil.mapColumnsToValues()`
- **Target**: `this.$mapResults()` (already exists in PlatformServiceMixin)
- **Migration**: Replace with `this.$mapResults()`
- **Files to migrate**: All data processing components

### 🟡 **PRIORITY 2 - High Priority Functions**

#### 4. `updateDefaultSettings()` and `updateDidSpecificSettings()`

- **Usage**: 20+ files
- **Current**: `databaseUtil.updateDefaultSettings()` / `databaseUtil.updateDidSpecificSettings()`
- **Target**: `this.$saveSettings()` and `this.$saveUserSettings()` (already exist)
- **Migration**: Replace with existing mixin methods
- **Files to migrate**: Settings management components

#### 5. `parseJsonField()`

- **Usage**: 15+ files
- **Current**: `databaseUtil.parseJsonField()` or direct import
- **Target**: Add `$parseJson()` method to PlatformServiceMixin
- **Migration**: Replace with `this.$parseJson()`
- **Files to migrate**: Data processing components

#### 6. `generateInsertStatement()` and `generateUpdateStatement()`

- **Usage**: 10+ files
- **Current**: `databaseUtil.generateInsertStatement()` / `databaseUtil.generateUpdateStatement()`
- **Target**: `this.$insertEntity()` and `this.$updateEntity()` (expand existing methods)
- **Migration**: Replace with high-level entity methods
- **Files to migrate**: Data manipulation components

### 🟢 **PRIORITY 3 - Medium Priority Functions**

#### 7. `insertDidSpecificSettings()`

- **Usage**: 8 files
- **Current**: `databaseUtil.insertDidSpecificSettings()`
- **Target**: `this.$insertUserSettings()` (new method)
- **Migration**: Replace with new mixin method
- **Files to migrate**: Account creation and import components

#### 8. `debugSettingsData()`

- **Usage**: 5 files
- **Current**: `databaseUtil.debugSettingsData()`
- **Target**: `this.$debugSettings()` (new method)
- **Migration**: Replace with new mixin method
- **Files to migrate**: Debug and testing components

### 🔵 **PRIORITY 4 - Low Priority Functions**

#### 9. `retrieveSettingsForDefaultAccount()`

- **Usage**: 3 files
- **Current**: `databaseUtil.retrieveSettingsForDefaultAccount()`
- **Target**: `this.$getDefaultSettings()` (new method)
- **Migration**: Replace with new mixin method
- **Files to migrate**: Settings management components

#### 10. Memory logs and cleanup functions

- **Usage**: 2 files
- **Current**: `databaseUtil.memoryLogs`, cleanup functions
- **Target**: `this.$memoryLogs` and `this.$cleanupLogs()` (new methods)
- **Migration**: Replace with new mixin methods
- **Files to migrate**: Log management components

## Implementation Strategy

### Phase 0: Untangle Logger and DatabaseUtil (Prerequisite)

**This must be done FIRST to eliminate circular dependencies before any mixin migration.**

1. **Create self-contained logger.ts**:
   - Remove `import { logToDb } from "../db/databaseUtil"`
   - Add direct database access via `PlatformServiceFactory.getInstance()`
   - Implement `logger.toDb()` and `logger.toConsoleAndDb()` methods

2. **Remove databaseUtil imports from PlatformServiceMixin**:
   - Remove `import { mapColumnsToValues, parseJsonField } from "@/db/databaseUtil"`
   - Remove `import * as databaseUtil from "@/db/databaseUtil"`
   - Add self-contained implementations of utility methods

3. **Test logger independence**:
   - Verify logger works without databaseUtil
   - Ensure no circular dependencies exist
   - Test all logging functionality

### Phase 1: Add Missing Methods to PlatformServiceMixin

1. **Add logging methods** (now using independent logger):

   ```typescript
   $log(message: string, level?: string): Promise<void>
   $logError(message: string): Promise<void>
   ```

2. **Add JSON parsing method** (self-contained):

   ```typescript
   $parseJson<T>(value: unknown, defaultValue: T): T
   ```

3. **Add entity update method**:

   ```typescript
   $updateEntity(tableName: string, entity: Record<string, unknown>, whereClause: string, whereParams: unknown[]): Promise<boolean>
   ```

4. **Add user settings insertion**:

   ```typescript
   $insertUserSettings(did: string, settings: Partial<Settings>): Promise<boolean>
   ```

### Phase 2: File-by-File Migration

#### Migration Order (by priority)

**Prerequisite**: Phase 0 (Logger/DatabaseUtil untangling) must be completed first.

1. **Start with most critical files**:
   - `src/App.vue` (main application)
   - `src/views/AccountViewView.vue` (core account management)
   - `src/views/ContactsView.vue` (core contact management)

2. **Migrate high-usage components**:
   - All view files in `src/views/`
   - Core components in `src/components/`

3. **Migrate services and utilities**:
   - `src/libs/util.ts`
   - `src/services/` files
   - `src/utils/logger.ts`

4. **Migrate remaining components**:
   - Specialized components
   - Test files

### Phase 3: Cleanup and Validation

1. **Remove databaseUtil imports** from migrated files
2. **Update TypeScript interfaces** to reflect new methods
3. **Run comprehensive tests** to ensure functionality
4. **Remove unused databaseUtil functions** after all migrations complete

## Migration Commands Template

For each file migration:

```bash
# 1. Update imports
# Remove: import * as databaseUtil from "../db/databaseUtil";
# Add: import { PlatformServiceMixin } from "@/utils/PlatformServiceMixin";

# 2. Add mixin to component
# Add: mixins: [PlatformServiceMixin],

# 3. Replace function calls
# Replace: databaseUtil.retrieveSettingsForActiveAccount()
# With: this.$settings()

# 4. Test the migration
npm run test

# 5. Commit the change
git add .
git commit -m "Migrate [filename] from databaseUtil to PlatformServiceMixin"
```

## Benefits of Migration

1. **Reduced Boilerplate**: Eliminate repeated `PlatformServiceFactory.getInstance()` calls
2. **Better Caching**: Leverage existing caching in PlatformServiceMixin
3. **Consistent Error Handling**: Centralized error handling and logging
4. **Type Safety**: Better TypeScript integration with mixin methods
5. **Performance**: Cached platform service access and optimized database operations
6. **Maintainability**: Single source of truth for database operations

## Risk Mitigation

1. **Incremental Migration**: Migrate one file at a time to minimize risk
2. **Comprehensive Testing**: Test each migration thoroughly
3. **Rollback Plan**: Keep databaseUtil.ts until all migrations are complete
4. **Documentation**: Update documentation as methods are migrated

## Smart Logging Integration Strategy

### Current State Analysis

#### Current Logging Architecture

1. **`src/utils/logger.ts`** - Main logger with console + database logging
2. **`src/db/databaseUtil.ts`** - Database-specific logging (`logToDb`, `logConsoleAndDb`)
3. **Circular dependency** - logger.ts imports logToDb from databaseUtil.ts

#### Current Issues

- **Circular dependency** between logger and databaseUtil
- **Duplicate functionality** - both systems log to database
- **Inconsistent interfaces** - different method signatures
- **Scattered logging logic** - logging rules spread across multiple files

### Recommended Solution: Hybrid Approach (Option 3)

**Core Concept**: Enhanced logger + PlatformServiceMixin convenience methods with **zero circular dependencies**.

#### Implementation

```typescript
// 1. Enhanced logger.ts (single source of truth - NO databaseUtil imports)
export const logger = {
  // Existing methods...

  // New database-focused methods (self-contained)
  toDb: async (message: string, level?: string) => {
    // Direct database access without databaseUtil dependency
    const platform = PlatformServiceFactory.getInstance();
    await platform.dbExec("INSERT INTO logs (date, message) VALUES (?, ?)", [
      new Date().toDateString(),
      `[${level?.toUpperCase() || 'INFO'}] ${message}`
    ]);
  },

  toConsoleAndDb: async (message: string, isError?: boolean) => {
    // Console output
    if (isError) {
      console.error(message);
    } else {
      console.log(message);
    }
    // Database output
    await logger.toDb(message, isError ? 'error' : 'info');
  },

  // Component context methods
  withContext: (componentName?: string) => ({
    log: (message: string, level?: string) => logger.toDb(`[${componentName}] ${message}`, level),
    error: (message: string) => logger.toDb(`[${componentName}] ${message}`, 'error')
  })
};

// 2. PlatformServiceMixin convenience methods (NO databaseUtil imports)
methods: {
  $log(message: string, level?: string): Promise<void> {
    return logger.toDb(message, level);
  },

  $logError(message: string): Promise<void> {
    return logger.toDb(message, 'error');
  },

  $logAndConsole(message: string, isError = false): Promise<void> {
    return logger.toConsoleAndDb(message, isError);
  },

  // Self-contained utility methods (no databaseUtil dependency)
  $mapResults<T>(results: QueryExecResult | undefined, mapper: (row: unknown[]) => T): T[] {
    if (!results) return [];
    return results.values.map(mapper);
  },

  $parseJson<T>(value: unknown, defaultValue: T): T {
    if (typeof value === 'string') {
      try {
        return JSON.parse(value);
      } catch {
        return defaultValue;
      }
    }
    return value as T || defaultValue;
  }
}
```

#### Benefits

1. **Single source of truth** - logger.ts handles all database logging
2. **No circular dependencies** - logger.ts doesn't import from databaseUtil
3. **Component convenience** - PlatformServiceMixin provides easy access
4. **Backward compatibility** - existing code can be migrated gradually
5. **Context awareness** - logging can include component context
6. **Performance optimized** - caching and batching in logger

#### Migration Strategy

1. **Phase 1**: Create self-contained logger.ts with direct database access (no databaseUtil imports)
2. **Phase 2**: Add self-contained convenience methods to PlatformServiceMixin (no databaseUtil imports)
3. **Phase 3**: Migrate existing code to use new methods
4. **Phase 4**: Remove old logging methods from databaseUtil
5. **Phase 5**: Remove databaseUtil imports from PlatformServiceMixin

#### Key Features

- **Smart filtering** - prevent logging loops and initialization noise
- **Context tracking** - include component names in logs
- **Performance optimization** - batch database writes
- **Error handling** - graceful fallback when database unavailable
- **Platform awareness** - different behavior for web/mobile/desktop

### Integration with Migration Plan

This logging integration will be implemented as part of **Phase 1** of the migration plan, specifically:

1. **Add logging methods to PlatformServiceMixin** (Priority 1, Item 2)
2. **Migrate logConsoleAndDb and logToDb usage** across all files
3. **Consolidate logging logic** in logger.ts
4. **Remove circular dependencies** between logger and databaseUtil

---

**Author**: Matthew Raymer
**Created**: 2025-07-05
**Status**: Planning Phase
**Last Updated**: 2025-07-05
