using ComputerSalesApp.Data;
using ComputerSalesApp.Models;
using Npgsql;

namespace ComputerSalesApp.Services;

internal sealed class AuthService
{
    public async Task<UserSession?> AuthenticateAsync(string login, string password)
    {
        await using var connection = Db.CreateConnection();
        await connection.OpenAsync();

        string sql = $@"
select
    user_id,
    login,
    role::text as role,
    customer_id
from {ConnectionSettings.Schema}.fn_authenticate_user(@login, @password);";

        await using var command = new NpgsqlCommand(sql, connection);
        command.Parameters.AddWithValue("login", login);
        command.Parameters.AddWithValue("password", password);

        await using var reader = await command.ExecuteReaderAsync();
        if (!await reader.ReadAsync())
        {
            return null;
        }

        return new UserSession
        {
            UserId = reader.GetInt32(reader.GetOrdinal("user_id")),
            Login = reader.GetString(reader.GetOrdinal("login")),
            Role = reader.GetString(reader.GetOrdinal("role")),
            CustomerId = reader.IsDBNull(reader.GetOrdinal("customer_id"))
                ? null
                : reader.GetInt32(reader.GetOrdinal("customer_id"))
        };
    }
}
