import 'dart:developer';
import 'dart:io';

import 'package:sqflite/sqflite.dart';

class DatabaseErrorHandler {
  static Future<T> executeWithRetry<T>(
    Future<T> Function() operation, {
    int maxRetries = 3,
    Duration delay = const Duration(milliseconds: 500),
  }) async {
    int attempts = 0;

    while (attempts < maxRetries) {
      try {
        return await operation();
      } catch (e) {
        attempts++;

        if (attempts >= maxRetries) {
          rethrow;
        }

        log('Database operation failed (attempt $attempts/$maxRetries): $e');
        await Future.delayed(delay * attempts);
      }
    }

    throw Exception('Max retries exceeded');
  }

  static bool isDatabaseCorrupted(dynamic error) {
    final errorString = error.toString().toLowerCase();
    return errorString.contains('corrupt') ||
        errorString.contains('malformed') ||
        errorString.contains('no such table');
  }

  static Future<void> handleDatabaseCorruption() async {
    try {
      // Delete corrupted database
      final dbPath = await getDatabasesPath();
      final file = File('$dbPath/pos_database.db');
      if (await file.exists()) {
        await file.delete();
      }

      log('Corrupted database deleted, will be recreated');
    } catch (e) {
      log('Error handling database corruption: $e');
    }
  }
}
