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

namespace IWS5.DatabaseAccess.Repositories;

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