using Microsoft.EntityFrameworkCore;

using Monitoring.Core.Domain.UserSettingsManagement;
using Monitoring.Core.Domain.UserPrimitives;
using Monitoring.Core.Domain.AssetGroupManagement;
using Monitoring.Infrastructure.Data;

namespace Monitoring.Repositories;

public class UserSettingsRepository(
	DataContext dataContext
)
{
	public Task<UserSettings?> GetByUserId(UserId userId, CancellationToken cancellationToken)
	{
		return dataContext.UserSettings
			.FirstOrDefaultAsync(x => x.UserId == userId, cancellationToken);
	}

	public async Task<UserSettings> CreateOrUpdate(
		UserId userId,
		PositioningStrategy positioningStrategy,
		ManualPosition? manualPosition = null,
		AssetGroupId? assetGroupId = null,
		CancellationToken cancellationToken = default)
	{
		var existingSettings = await GetByUserId(userId, cancellationToken);

		if (existingSettings is null)
		{
			existingSettings = UserSettings.Create(userId, positioningStrategy, manualPosition, assetGroupId);
			await dataContext.UserSettings.AddAsync(existingSettings, cancellationToken);
		}
		else
		{
			existingSettings.Update(positioningStrategy, manualPosition, assetGroupId);
		}

		await dataContext.SaveChangesAsync(cancellationToken);
		return existingSettings;
	}
} 