import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:uuid/uuid.dart';

import '../models/document.dart';
import '../services/database_service.dart';
import 'note_provider.dart';

const _uuid = Uuid();

final documentListProvider =
    AsyncNotifierProvider<DocumentListNotifier, List<Document>>(
      DocumentListNotifier.new,
    );

class DocumentListNotifier extends AsyncNotifier<List<Document>> {
  Future<DatabaseService> get _db => ref.read(databaseServiceProvider.future);

  @override
  Future<List<Document>> build() async {
    final db = await _db;
    return db.getAllDocuments();
  }

  /// Reloads documents from the database and publishes the result to [state]
  /// so the UI rebuilds. Used by pull-to-refresh.
  Future<void> loadDocuments() async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(() async {
      final db = await _db;
      return db.getAllDocuments();
    });
  }

  Future<Document> addDocument({
    required String filename,
    required String docType,
    required String filePath,
    int pageCount = 0,
  }) async {
    final db = await _db;
    final now = DateTime.now();
    final document = Document(
      id: _uuid.v4(),
      filename: filename,
      docType: docType,
      filePath: filePath,
      pageCount: pageCount,
      createdAt: now,
      updatedAt: now,
    );
    await db.insertDocument(document);
    state = AsyncData([document, ...state.value ?? []]);
    return document;
  }

  Future<void> removeDocument(String id) async {
    final db = await _db;
    await db.deleteDocument(id);
    final current = state.value ?? [];
    state = AsyncData(current.where((d) => d.id != id).toList());
  }
}
