using Microsoft.EntityFrameworkCore;
using Strata.Code.DataAccess.Data;
using Strata.Code.DataAccess.Models;
using Strata.Code.DataAccess.Repositories.Interfaces;

namespace Strata.Code.DataAccess.Repositories
{
    public class BudgetConfigDefaultSettingRepository : IBudgetConfigDefaultSettingRepository
    {
        private readonly OnePlanDbContext _context;

        public BudgetConfigDefaultSettingRepository(OnePlanDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public async Task<IEnumerable<BudgetConfigDefaultSetting>> GetAllAsync()
        {
            return await _context.Set<BudgetConfigDefaultSetting>()
                .ToListAsync();
        }

        public async Task<BudgetConfigDefaultSetting?> GetByIdAsync(int id)
        {
            return await _context.Set<BudgetConfigDefaultSetting>()
                .FirstOrDefaultAsync(x => x.SettingId == id);
        }

        public async Task<BudgetConfigDefaultSetting> CreateAsync(BudgetConfigDefaultSetting setting)
        {
            setting.DateCreated = DateOnly.FromDateTime(DateTime.UtcNow);
            await _context.Set<BudgetConfigDefaultSetting>().AddAsync(setting);
            await _context.SaveChangesAsync();

            return setting;
        }

        public async Task<BudgetConfigDefaultSetting?> UpdateAsync(BudgetConfigDefaultSetting setting)
        {
            var existingSetting = await GetByIdAsync(setting.SettingId);
            if (existingSetting == null)
                return null;

            existingSetting.Name = setting.Name;
            existingSetting.DefaultValue = setting.DefaultValue;
            existingSetting.Description = setting.Description;

            _context.Set<BudgetConfigDefaultSetting>().Update(existingSetting);
            await _context.SaveChangesAsync();

            return existingSetting;
        }

        public async Task<bool> DeleteAsync(int id)
        {
            var setting = await GetByIdAsync(id);
            if (setting == null)
                return false;

            _context.Remove(setting);
            await _context.SaveChangesAsync();

            return true;
        }
    }
}
