import 'package:backend_dart/domain/entities/user.dart';
import 'package:backend_dart/domain/repositories/user_repository.dart';
import 'package:postgres/postgres.dart';

class PostgresUserRepository implements UserRepository {
  final PostgreSQLConnection connection;

  PostgresUserRepository(this.connection);

  @override
  Future<void> create(User user) async {
    await connection.query(
      'INSERT INTO users (id, name, email, password) VALUES (@id, @name, @mail, @pwd)',
      substitutionValues: {
        'id': user.id,
        'name': user.name,
        'mail': user.email,
        'pwd': user.password,
      },
    );
  }

  @override
  Future<User?> findByEmail(String email) async {
    final results = await connection.query(
      'SELECT id, name, email, password FROM users WHERE email = @mail',
      substitutionValues: {'mail': email},
    );

    if (results.isNotEmpty) {
      final row = results.first;
      return User(
        id: row[0],
        name: row[1],
        email: row[2],
        password: row[3],
      );
    }
    return null;
  }

  @override
  Future<User?> findById(String id) async {
    final results = await connection.query(
      'SELECT id, name, email, password FROM users WHERE id = @id',
      substitutionValues: {'id': id},
    );

    if (results.isNotEmpty) {
      final row = results.first;
      return User(
        id: row[0],
        name: row[1],
        email: row[2],
        password: row[3],
      );
    }
    return null;
  }
}
