import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';

import '../../utils/downloads/download_job.dart';
import '../../utils/downloads/download_manager.dart';
import '../confirm_dialog.dart';
import '../info_dialog.dart';

/// Verifies a finished download's cache file is still on disk before opening.
///
/// Downloads live in the app's temp dir, which Android may clear at any time
/// (storage pressure, "Cache leeren") — while completion notifications and
/// tray entries stay tappable indefinitely. Returns true when the file exists;
/// otherwise drops the stale job (incl. its notification) and offers a
/// re-download when the remote path is known (it isn't for notification taps
/// whose task metadata got lost).
bool ensureDownloadStillExists(BuildContext context, DownloadJob job) {
  final path = job.localPath;
  if (path == null || File(path).existsSync()) return true;

  DownloadManager.instance.markOpened(job);
  if (job.remotePath.isNotEmpty) {
    ConfirmDialog(
      title: 'Datei nicht mehr verfügbar',
      content:
          'Die heruntergeladene Datei wurde vom System aus dem Zwischenspeicher entfernt.\nErneut herunterladen?',
      confirmButton: 'Herunterladen',
      onConfirm: () => unawaited(DownloadManager.instance.retry(job)),
    ).asDialog(context);
  } else {
    InfoDialog.show(
      context,
      'Die heruntergeladene Datei wurde vom System aus dem Zwischenspeicher entfernt. Bitte lade sie erneut herunter.',
      title: 'Datei nicht mehr verfügbar',
    );
  }
  return false;
}
