using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Npgsql;
using Tiss.Domain.Repositories;
using Tiss.Domain.Users.Models;
using Tiss.Infra.Repositories.User.Entities;
using Tiss.Infra.Repositories.User.Queries;
using Tiss.Shared.EnvironmentVariables;
namespace Tiss.Infra.Repositories.User;
public class PostgresqlUserRepository : IUserRepository
{
private readonly NpgsqlConnection _connection;
private readonly UserTableQueries _queries = new();
public PostgresqlUserRepository(ApplicationEnvVars applicationEnvVars)
{
_connection = new NpgsqlConnection(applicationEnvVars.PostgreSqlEnvVars.ConnectionString);
_connection.Open();
}
public async Task<UserModel?> GetUserByTaxId(string taxId)
{
try
{
var dynamicParameters = new DynamicParameters();
dynamicParameters.Add("TaxId", taxId);
var queryResult = await _connection.QueryAsync<UserEntity>(_queries.GetUserByTaxId(), dynamicParameters);
var userModel = ToDomain(queryResult);
return userModel;
}
catch (Exception e)
{
// TODO: add logger;
Console.WriteLine(e);
throw;
}
}
private UserModel ToDomain(IEnumerable<UserEntity> userEntities) =>
new()
{
Name = userEntities.First().Name,
Password = userEntities.First().Password,
Email = userEntities.First().Email,
TaxId = userEntities.First().TaxId,
RelatedCompanies = userEntities.Select(v => v.CompanyId).ToList()
};
}