import { db } from '../../config/database'

export const queueStore = {
  getPending() {
    return db.prepare(`
      SELECT * FROM sync_log 
      WHERE status = 'pending' 
      ORDER BY created_at ASC
    `).all() as any[]
  },
  markCompleted(id: string) {
    db.prepare(`UPDATE sync_log SET status = 'completed', completed_at = ? WHERE id = ?`).run(new Date().toISOString(), id)
  },
  markFailed(id: string, message: string) {
    db.prepare(`UPDATE sync_log SET status = 'failed', error_message = ? WHERE id = ?`).run(message, id)
  },
  updateMetadata(nodeId: string, result: { success: boolean; syncedItems: number; conflicts: any[]; errors: any[] }) {
    const existing = db.prepare('SELECT * FROM sync_metadata WHERE node_id = ?').get(nodeId) as any
    if (existing) {
      db.prepare(`
        UPDATE sync_metadata SET
          last_sync_at = ?,
          last_successful_sync = ?,
          total_synced_items = total_synced_items + ?,
          total_conflicts = total_conflicts + ?,
          total_errors = total_errors + ?
        WHERE node_id = ?
      `).run(
        new Date().toISOString(),
        result.success ? new Date().toISOString() : existing.last_successful_sync,
        result.syncedItems,
        result.conflicts.length,
        result.errors.length,
        nodeId
      )
    } else {
      db.prepare(`
        INSERT INTO sync_metadata (
          node_id, last_sync_at, last_successful_sync,
          total_synced_items, total_conflicts, total_errors
        ) VALUES (?, ?, ?, ?, ?, ?)
      `).run(
        nodeId,
        new Date().toISOString(),
        result.success ? new Date().toISOString() : null,
        result.syncedItems,
        result.conflicts.length,
        result.errors.length
      )
    }
  },
  getSyncSettings() {
    const settings = db.prepare('SELECT * FROM sync_settings WHERE id = ?').get('default') as any
    return settings || { autoSyncInterval: 'disabled', conflictResolution: 'admin' }
  },
  getNodeInfo(nodeId: string) {
    return db.prepare('SELECT * FROM network_nodes WHERE id = ?').get(nodeId)
  }
}

