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

namespace IWS5.DatabaseAccess.Repositories;

public class FieldInstanceNumberRepository(GreenfieldPd2015Context context)
    : IWSRepository<AtfieldInstanceNumber>(context), IFieldInstanceNumberRepository
{
    public async Task<bool> UpdateOrInsertValueAsync(int fieldId, int workItemId, decimal newValue)
    {
        var fieldToUpdate = await context.AtfieldInstanceNumbers.FirstOrDefaultAsync(fis => fis.WorkItemId == workItemId &&  fis.FieldId == fieldId);
        if (fieldToUpdate == null)
        {
            fieldToUpdate = new AtfieldInstanceNumber()
            {
                WorkItemId = workItemId,
                FieldId = fieldId,
                FieldValue = newValue
            };
            context.AtfieldInstanceNumbers.Add(fieldToUpdate);
            return await context.SaveChangesAsync() > 0;
        }
        fieldToUpdate.FieldValue = newValue;
        return await context.SaveChangesAsync() > 0;
    }
}