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

namespace IWS5.DatabaseAccess.Repositories;

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