using Lactose.Context;
using Lactose.Models;
using System.Data;

namespace Lactose.Repositories;

public class SettingsRepository(LactoseDbContext context) : ISettingsRepository {
    public void Create(Setting setting) {
        //Check if the settings already exist
        var existingSettings = context.Settings.FirstOrDefault(s => s.Name == setting.Name);
        if (existingSettings != null) 
            throw new DuplicateNameException("A setting with the same key already exists: " + setting.Name);

        //Adds the new settings
        context.Settings.Add(setting);
    }
    
    public IEnumerable<Setting> Get() => context.Settings.AsEnumerable();

    public Setting? Get(string name) => context.Settings.FirstOrDefault(s => s.Name == name);

    public void Update(Setting setting) {
        var existingSettings = context.Settings.FirstOrDefault(s => s.Name == setting.Name);
        if (existingSettings != null) {
            existingSettings.Value = setting.Value;
            context.Settings.Update(existingSettings);
        } else {
            // If the settings entry does not exist
            throw new KeyNotFoundException("The setting with the specified name does not exist: " + setting.Name);
        }
    }

    public void Delete() => context.Settings.RemoveRange(context.Settings);
 
    public void Delete(Setting setting) {
        var existingSettings = context.Settings.FirstOrDefault(s => s.Name == setting.Name);
        if (existingSettings != null) {
            context.Settings.Remove(existingSettings);
        } else {
            // If the settings entry does not exist
            throw new KeyNotFoundException("The setting with the specified name does not exist: " + setting.Name);
        }
    }
    public void Delete(string name) {
        var existingSettings = context.Settings.FirstOrDefault(s => s.Name == name);
        if (existingSettings == null) throw new KeyNotFoundException("The setting with the specified name does not exist: " + name);
        Delete(existingSettings);
    }
}