import { db } from '../db/database.js'
import { formatBackupFilename } from '../utils/backupFilename.js'
import { useBackupStatus } from './useBackupStatus.js'
import { useSaveFilePrompt } from './useSaveFilePrompt.js'

export function useBackupDownload() {
  const { markBackedUp } = useBackupStatus()
  const { promptFilename } = useSaveFilePrompt()

  /**
   * Prompts for a filename, exports the database, triggers a file download,
   * and records last_backup_at. Returns false without side effects if cancelled.
   */
  async function downloadBackup() {
    const filename = await promptFilename(formatBackupFilename(__APP_VERSION__))
    if (!filename) return false

    const bytes = await db.exportDatabase()
    const blob = new Blob([bytes], { type: 'application/x-sqlite3' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = filename
    a.click()
    URL.revokeObjectURL(url)
    await markBackedUp()
    return true
  }

  return { downloadBackup }
}
