using CSharpFunctionalExtensions;
using Microsoft.EntityFrameworkCore;
using Monitoring.Core.Domain;
using Monitoring.Core.Domain.AssetManagement;
using Monitoring.Core.Domain.UserLogManagement;
using Monitoring.Core.Domain.UserPrimitives;
using Monitoring.Infrastructure.Data;
using Monitoring.Models;
using Monitoring.Services;

namespace Monitoring.Repositories;

public class UserLogRepository(
	DataContext dataContext,
	AssetRepository assetRepository,
	UsersService usersService,
	INotificationService notificationService
)
{
	public async Task<Result<UserLog>> Create(
		AssetId assetId,
		UserId userId,
		UserLogInformation information,
		CancellationToken cancellationToken
	)
	{
		var asset = await assetRepository.Get(assetId, userId, cancellationToken);
		if (asset is null)
		{
			return Result.Failure<UserLog>("Asset not found");
		}

		var log = UserLog.Create(userId, assetId, information);
		_ = await dataContext.UserLogs.AddAsync(log, cancellationToken);
		_ = await dataContext.SaveChangesAsync(cancellationToken);

		var model = await dataContext
			.UserLogs.Where(x => x.Id == log.Id)
			.Select(UserLogModel.FromEntity)
			.FirstAsync(cancellationToken);

		var userIds = await usersService.GetWatcherIdListByAsset(assetId, cancellationToken);

		await notificationService.NotifyUsers(userIds, "LOGS.CREATED", model, cancellationToken);

		return Result.Success(log);
	}
}
