// lib/remote/run_remote_sync.dart
import 'package:aves/services/common/services.dart';
import 'package:aves/model/db/db.dart'; // LocalMediaDb
import 'package:aves/remote/remote_repository.dart';
import 'package:aves/remote/remote_models.dart'; // RemotePhotoItem
import 'package:flutter/foundation.dart' show debugPrint;
import 'package:sqflite/sqflite.dart';

import 'remote_origin.dart';

/// Esegue un giro di sync remoto riusando **la stessa connessione** del loader (4A).
/// Passa una funzione `fetch` che ritorna la lista di RemotePhotoItem da importare.
/// Ritorna il numero di elementi **nuovi/aggiornati** importati.
Future<int> runRemoteSyncOnceManaged({
  required Future<List<RemotePhotoItem>> Function() fetch,
}) async {
  try {
    // 1) Usa la **stessa connessione** del loader
    final localDb = getIt<LocalMediaDb>();
    final db = localDb.rawDb;
    final repo = RemoteRepository(db);

    // 2) Conteggio pre (diagnostica)
    final pre = (Sqflite.firstIntValue(
          await db.rawQuery(
            'SELECT COUNT(*) FROM entry WHERE origin=?',
            [RemoteOrigin.value],
          ),
        ) ??
        0);
    debugPrint('[remote-sync][pre] count origin=${RemoteOrigin.value} = $pre');

    // 3) Fetch dal server
    final items = await fetch();
    debugPrint('[remote-sync] fetchAll done, items=${items.length}');

    if (items.isEmpty) {
      debugPrint('[remote-sync] no items to import, exiting');
      return 0;
    }

    // 4) Upsert + sanitize
    final sw = Stopwatch()..start();
    await repo.upsertAll(items);
    await repo.sanitizeRemotes();
    sw.stop();
    debugPrint('[remote-sync] upsert+sanitize completed in ${sw.elapsedMilliseconds}ms');

    // 5) Conteggio post e sample (diagnostica)
    final post = (Sqflite.firstIntValue(
          await db.rawQuery(
            'SELECT COUNT(*) FROM entry WHERE origin=?',
            [RemoteOrigin.value],
          ),
        ) ??
        0);
    debugPrint('[remote-sync][post] count origin=${RemoteOrigin.value} = $post');

    final sample = await db.rawQuery(
      'SELECT id, remoteId, provider, uri, trashed, dateModifiedMillis '
      'FROM entry WHERE origin=? ORDER BY id DESC LIMIT 3',
      [RemoteOrigin.value],
    );
    debugPrint('[remote-sync][post] sample origin=${RemoteOrigin.value} = $sample');

    return (post - pre).clamp(0, items.length);
  } catch (e, st) {
    debugPrint('[remote-sync] ERROR: $e\n$st');
    return 0;
  }
}

