using Microsoft.EntityFrameworkCore;

using Monitoring.Core.Domain.ServiceOrganizationManagement;
using Monitoring.Infrastructure.Data;

namespace Monitoring.Repositories;

public class ServiceOrganizationRepository : IServiceOrganizationRepository
{
  private readonly DataContext _dbContext;

  public ServiceOrganizationRepository(DataContext dbContext)
  {
    _dbContext = dbContext;
  }

  public async Task<List<ServiceOrganization>>  GetAll()
  {
    return await _dbContext.ServiceOrganizations.ToListAsync();
  }

 public async Task<ServiceOrganization> GetById(Guid id)
{
    var serviceOrganizationId = new ServiceOrganizationId(id);
    return await _dbContext.ServiceOrganizations!
        .FirstAsync(x => x.Id == serviceOrganizationId); 
}

  public async Task Create(ServiceOrganization organization)
  {
    // Don't override CreatedAt if it's already set in the domain entity
    if (organization.CreatedAt == default)
    {
      organization.CreatedAt = DateTime.UtcNow;
    }
        
    _dbContext.ServiceOrganizations.Add(organization);
    await _dbContext.SaveChangesAsync();
  }

  public async Task Update(ServiceOrganization organization)
  {
    organization.UpdatedAt = DateTime.UtcNow;
    _dbContext.ServiceOrganizations.Update(organization);
    await _dbContext.SaveChangesAsync();
  }

  public async Task Delete(Guid id)
  {
    var serviceOrganizationId = new ServiceOrganizationId(id);
    var organization = await _dbContext.ServiceOrganizations
      .FirstOrDefaultAsync(x => x.Id == serviceOrganizationId);
            
    if (organization != null)
    {
      _dbContext.ServiceOrganizations.Remove(organization);
      await _dbContext.SaveChangesAsync();
    }
  }
}