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

namespace IWS5.DatabaseAccess.Repositories;

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