namespace OpenWarehouse.warehouse.api.Common.ServiceClaims;

public class ServiceClaimsManager(ApplicationDbContext context) : IServiceClaimsManager
{
    public async Task<Claim> GetServiceClaims(ServiceClaim claim)
    {
        var result = await context.ServiceClaims
            .Where(claims => claims.ClaimType == claim.GetName())
            .FirstOrDefaultAsync();
        if (result == null)
        {
            return new Claim(claim.GetName(), "");
        }

        return result.Claim;
    }

    public async Task<List<Claim>> GetListServiceClaims()
    {
        return await context.ServiceClaims.Select(q => new Claim(q.ClaimType ?? "Uknow", q.ClaimValue ?? "")).ToListAsync();
    }

    public async Task<bool> UpdateClaim(ServiceClaim claim, string value)
    {
        var result = await context.ServiceClaims
            .Where(claims => claims.ClaimType == claim.GetName())
            .FirstOrDefaultAsync();
        if (result == null)
        {
            Data.ServiceClaims claims = claim.CreateServiceClaims(value);
            context.ServiceClaims.Add(claims);
        }
        else
        {
            result.ClaimValue = value;
        }

        var res = await context.SaveChangesAsync();

        return res > 0;
    }

    public async Task<bool> ClaimIsSet(ServiceClaim claim)
    {
        var result = await context.ServiceClaims
            .Where(q => q.ClaimType == claim.GetName()).AnyAsync();
        
        return result;
    }
}