import 'package:riverpod_annotation/riverpod_annotation.dart';

import 'package:household_keeper/core/database/database.dart';
import 'package:household_keeper/core/providers/database_provider.dart';
import 'package:household_keeper/features/rooms/data/rooms_dao.dart';

part 'room_providers.g.dart';

/// Watches all rooms with computed task stats (due count, cleanliness ratio).
@riverpod
Stream<List<RoomWithStats>> roomWithStatsList(Ref ref) {
  final db = ref.watch(appDatabaseProvider);
  return db.roomsDao.watchRoomWithStats();
}

/// Async notifier for room mutation actions (create, update, delete, reorder).
@riverpod
class RoomActions extends _$RoomActions {
  @override
  FutureOr<void> build() {}

  /// Create a new room. Returns the auto-generated id.
  Future<int> createRoom(String name, String iconName) async {
    final db = ref.read(appDatabaseProvider);
    return db.roomsDao.insertRoom(RoomsCompanion.insert(
      name: name,
      iconName: iconName,
    ));
  }

  /// Update an existing room.
  Future<void> updateRoom(Room room) async {
    final db = ref.read(appDatabaseProvider);
    await db.roomsDao.updateRoom(room);
  }

  /// Delete a room and cascade to its tasks and completions.
  Future<void> deleteRoom(int roomId) async {
    final db = ref.read(appDatabaseProvider);
    await db.roomsDao.deleteRoom(roomId);
  }

  /// Reorder rooms by their IDs in the new order.
  Future<void> reorderRooms(List<int> roomIds) async {
    final db = ref.read(appDatabaseProvider);
    await db.roomsDao.reorderRooms(roomIds);
  }
}
