using Microsoft.EntityFrameworkCore;
using OmsorgCore.Application.Abstractions;
using OmsorgCore.Domain.Entities;
using OmsorgCore.Infrastructure.Persistence;

namespace OmsorgCore.Infrastructure.Repositories;

public class AssignmentValidationSettingsRepository : IAssignmentValidationSettingsRepository
{
    private readonly OmsorgCoreDbContext _db;

    public AssignmentValidationSettingsRepository(OmsorgCoreDbContext db)
    {
        _db = db;
    }

    public async Task<AssignmentValidationSettings> GetOrCreateAsync(CancellationToken cancellationToken = default)
    {
        var settings = await _db.AssignmentValidationSettings.FirstOrDefaultAsync(cancellationToken);
        if (settings is not null)
        {
            return settings;
        }

        settings = new AssignmentValidationSettings();
        await _db.AssignmentValidationSettings.AddAsync(settings, cancellationToken);
        await _db.SaveChangesAsync(cancellationToken);
        return settings;
    }

    public Task UpdateAsync(AssignmentValidationSettings settings, CancellationToken cancellationToken = default)
    {
        _db.AssignmentValidationSettings.Update(settings);
        return Task.CompletedTask;
    }

    public Task SaveChangesAsync(CancellationToken cancellationToken = default)
        => _db.SaveChangesAsync(cancellationToken);
}
