using IWS5.DatabaseAccess.Interfaces;
using IWS5.DatabaseAccess.IwsDataContext;
using IWS5.DatabaseAccess.IwsDataModels;
using Microsoft.EntityFrameworkCore;
using Serilog;

namespace IWS5.DatabaseAccess.Repositories;

public class UserRepository(GreenfieldPd2015Context context, ILogger logger) 
    : IWSRepository<Atuser>(context), IUserRepository
{
    public async Task<Atuser> GetUserWithGroupsAsync(string userName)
    {
        logger.Information("Starting GetUserWithGroupsAsync for user: {UserName}", userName);
        
        var userQuery = context.Atusers.AsNoTracking().Select(atUser => new Atuser
        {
            UserName = atUser.UserName,
            DisplayName = atUser.DisplayName,
            ObjectId = atUser.ObjectId,
            AtuserProperties = atUser.AtuserProperties
                .Where(userProperty => userProperty.UserName == userName && (userProperty.PropertyName == "Email" || userProperty.PropertyName == "Password"))
                .Select(userProperty => new AtuserProperty
                {
                    UserName = userProperty.UserName,
                    PropertyName = userProperty.PropertyName,
                    PropertyValue = userProperty.PropertyValue
                })
                .ToList(),
            Parents = atUser.Parents.Select(g => new Atuser
            {
                UserName = g.UserName,
                DisplayName = g.DisplayName,
                ObjectId = g.ObjectId
            }).ToList()
        }).Where(atUser => atUser.UserName.ToLower() == userName.ToLower());
        
        var queryString = userQuery.ToQueryString();
        logger.Information("Generated SQL query for GetUserWithGroupsAsync: {Query}", queryString);
        var userQueryResult = await userQuery.FirstOrDefaultAsync();
        
        if (userQueryResult == null)
        {
            logger.Warning("No user found for username: {UserName}", userName);
        }
        else
        {
            logger.Information("User found for username: {UserName}", userName);
        }
        
        return userQueryResult;
    }
}