import * as FileSystem from 'expo-file-system/legacy';

const DB_PATH = `${FileSystem.documentDirectory}SQLite/WatermelonDB.db`;
const BACKUP_PATH = `${FileSystem.documentDirectory}backups/backup.db`;

export async function createLocalBackup() {
  try {
    await FileSystem.makeDirectoryAsync(`${FileSystem.documentDirectory}backups/`, {
      intermediates: true
    });
    await FileSystem.copyAsync({ from: DB_PATH, to: BACKUP_PATH });
  } catch (e) {
    console.error('Backup failed', e);
  }
}

export async function hasLocalBackup() {
  const info = await FileSystem.getInfoAsync(BACKUP_PATH);
  return info.exists;
}

export async function restoreFromBackup() {
  try {
    const info = await FileSystem.getInfoAsync(BACKUP_PATH);
    if (!info.exists) return false;
    await FileSystem.copyAsync({ from: BACKUP_PATH, to: DB_PATH });
    return true;
  } catch (e) {
    console.error('Restore failed', e);
    return false;
  }
}
