import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

Future<void> copyDatabase(BuildContext context) async {
  try {
    Directory appDocDir = await getApplicationDocumentsDirectory();

    List<String> dbPaths = [
      '${appDocDir.path}/databases/conalepPos7.db',
      '${appDocDir.path}/conalepPos7.db',
      '/data/data/com.example.conalep_pos/databases/conalepPos7.db',
    ];

    File? dbFile;
    for (String path in dbPaths) {
      if (await File(path).exists()) {
        dbFile = File(path);
        break;
      }
    }

    if (dbFile != null) {
      Directory? downloadsDir = await getExternalStorageDirectory();
      if (downloadsDir == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
              content: Text('No se pudo acceder al directorio de descargas.')),
        );
        return;
      }

      String newPath = '${downloadsDir.path}/conalepPos7_backup.db';

      await dbFile.copy(newPath);

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text('Copia de la base de datos guardada en Descargas.')),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text(
                'El archivo de la base de datos no existe en ninguna de las rutas verificadas.')),
      );
    }
  } catch (e) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Error al copiar la base de datos: $e')),
    );
  }
}
