// lib/providers/notebook_container_provider.dart
//
// Home-screen list of OneNote-style notebook containers: vault folders that
// hold a `notebook.json` manifest (see `storage/notebook_manifest.dart`). This
// mirrors `note_provider.dart` / `document_provider.dart`'s vault-scan pattern
// — the manifest on disk is the source of truth, there is no SQLite cache.

import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../services/vault_service.dart';
import 'document_provider.dart' show vaultServiceProvider;

final notebookContainerListProvider = AsyncNotifierProvider<
    NotebookContainerListNotifier, List<VaultContainer>>(
  NotebookContainerListNotifier.new,
);

class NotebookContainerListNotifier
    extends AsyncNotifier<List<VaultContainer>> {
  Future<VaultService> get _vault => ref.read(vaultServiceProvider.future);

  @override
  Future<List<VaultContainer>> build() => _scan();

  Future<List<VaultContainer>> _scan() async {
    final vault = await _vault;
    return vault.scanContainers();
  }

  /// Re-scan the vault and publish the result. Used by pull-to-refresh and
  /// after a container is created elsewhere.
  Future<void> loadContainers() async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(_scan);
  }

  /// Create a new notebook container (folder + `notebook.json` + one blank ink
  /// page) titled [title], prepend it to the list, and return it so the caller
  /// can navigate straight into it.
  Future<VaultContainer> createContainer(String title) async {
    final vault = await _vault;
    final container = await vault.createNotebookContainer(title);
    state = AsyncData([container, ...state.value ?? []]);
    return container;
  }
}
