import 'repository.dart';
import 'package:sqflite/sqflite.dart';

class SQLiteRepository<T> implements Repository<T> {
  final Database database;
  final String tableName;
  final T Function(Map<String, dynamic>) fromMap;
  final Map<String, dynamic> Function(T) toMap;

  SQLiteRepository({
    required this.database,
    required this.tableName,
    required this.fromMap,
    required this.toMap,
  });

  @override
  Future<T?> consultarPorId(int id) async {
    final maps = await database.query(
      tableName,
      where: 'id = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return fromMap(maps.first);
    }
    return null;
  }

  @override
  Future<void> guardar(T entidad) async {
    final map = toMap(entidad);
    await database.insert(tableName, map,
        conflictAlgorithm: ConflictAlgorithm.replace);
  }

  @override
  Future<void> eliminar(int id) async {
    await database.delete(tableName, where: 'id = ?', whereArgs: [id]);
  }

  @override
  Future<List<T>> consultarConOrden(
      {String? orderBy,
      int? limit,
      int? offset,
      String? where,
      List<Object?>? whereArgs}) async {
    final maps = await database.query(
      tableName,
      orderBy: orderBy,
      limit: limit,
      offset: offset,
      where: where,
      whereArgs: whereArgs,
    );

    return maps.map(fromMap).toList();
  }
}
