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

namespace IWS5.DatabaseAccess.Repositories;

public class PendingWorkItemReferenceRepository(
    GreenfieldPd2015Context context,
    ILogger logger) : IWSRepository<AtpendingWorkItemReference>(context), IPendingWorkItemReferenceRepository
{
    public async Task AddOrUpdateAsync(AtpendingWorkItemReference pendingWorkItemReference)
    {
        AtpendingWorkItemReference? existingEntity = await context.AtpendingWorkItemReferences
            .FirstOrDefaultAsync(x => x.PendingWorkItemReferenceId == pendingWorkItemReference.PendingWorkItemReferenceId);

        if (existingEntity is null)
        {
            context.AtpendingWorkItemReferences.Add(pendingWorkItemReference);
        }
        else
        {
            existingEntity.ExpirationTime = pendingWorkItemReference.ExpirationTime;
            existingEntity.CreatedTime = DateTime.UtcNow;
        }
        
        await context.SaveChangesAsync();
    }

    public async Task DeleteByWorkItemReferenceIdAsync(int workItemReferenceId)
    {
        await context.AtpendingWorkItemReferences
            .Where(x => x.PendingWorkItemReferenceId == workItemReferenceId)
            .ExecuteDeleteAsync();
    }
}
