using System.Globalization;
using IWS5.Core.Constants;
using IWS5.DatabaseAccess.Interfaces;
using IWS5.DatabaseAccess.IwsDataContext;
using IWS5.DatabaseAccess.IwsDataModels;
using Microsoft.EntityFrameworkCore;

namespace IWS5.DatabaseAccess.Repositories;

public class UserPropertyRepository(GreenfieldPd2015Context context)
    : IWSRepository<AtuserProperty>(context), IUserPropertyRepository
{
    public async Task<bool> AddOrUpdateRefreshTokenData(string userName, string refreshToken,
        DateTime refreshTokenExpiry)
    {
        var refreshTokenRowData = await context.AtuserProperties
            .FirstOrDefaultAsync(uProperty => uProperty.PropertyName == AuthenticationConstants.RefreshTokenPropertyName
                                              && uProperty.UserName.ToLower() == userName.ToLower());
        if (refreshTokenRowData !=null ) context.AtuserProperties.RemoveRange(refreshTokenRowData);
        var newRefreshTokenRow = new AtuserProperty
        {
            UserName = userName,
            PropertyName = AuthenticationConstants.RefreshTokenPropertyName,
            PropertyValue = refreshToken
        };
        context.AtuserProperties.Add(newRefreshTokenRow);

        var refreshTokenExpiryRowData = await context.AtuserProperties
            .FirstOrDefaultAsync(uProperty =>
                uProperty.PropertyName == AuthenticationConstants.RefreshTokenExpiryPropertyName
                && uProperty.UserName.ToLower() == userName.ToLower());
        if (refreshTokenExpiryRowData != null) context.AtuserProperties.RemoveRange(refreshTokenExpiryRowData);
        var newRefreshTokenExpiryRow = new AtuserProperty
        {
            UserName = userName,
            PropertyName = AuthenticationConstants.RefreshTokenExpiryPropertyName,
            PropertyValue = refreshTokenExpiry.ToString(CultureInfo.InvariantCulture)
        };
        context.Add(newRefreshTokenExpiryRow);

        var update = await context.SaveChangesAsync();
        return update > 0;
    }

    public async Task<bool> RemoveRefreshTokenData(string userName)
    {
        var refreshData = context.AtuserProperties
            .Where(uProperty => uProperty.UserName.ToLower() == userName.ToLower()
                                && (uProperty.PropertyName == AuthenticationConstants.RefreshTokenPropertyName
                                    || uProperty.PropertyName ==
                                    AuthenticationConstants.RefreshTokenExpiryPropertyName));
        if (refreshData.Any())
        {
            context.AtuserProperties.RemoveRange(refreshData);
            var success = await context.SaveChangesAsync();
            return success > 0;
        }

        return true;
    }
}