using Forwarder.Data;
using Forwarder.Domain;
using Forwarder.Models;

using Microsoft.EntityFrameworkCore;

namespace Forwarder.Repositories.Implementations;

/// <inheritdoc />
public sealed class MessageRepository(
	DataContext dataContext
) : IMessageRepository
{
	/// <inheritdoc />
	public async Task<Result> AddAsync(Message message, CancellationToken cancellationToken)
	{
		try
		{
			_ = await dataContext.Messages.AddAsync(message, cancellationToken);
			_ = await dataContext.SaveChangesAsync(cancellationToken);

			return Result.Success();
		}
		catch (Exception ex)
		{
			return Result.Fail(ex.Message);
		}
	}

	/// <inheritdoc />
	public Task<List<Message>> GetFirstListAsync(int takeCount, CancellationToken cancellationToken)
	{
		return dataContext.Messages
			.Take(takeCount)
			.ToListAsync(cancellationToken);
	}

	/// <inheritdoc />
	public async Task<Result> RemoveAsync(Message message, CancellationToken cancellationToken)
	{
		var existingMessage = await dataContext.Messages
			.FirstOrDefaultAsync(x => x.Id == message.Id, cancellationToken);
		if (existingMessage is null)
		{
			return Result.Fail("Сообщение не найдено");
		}

		_ = dataContext.Messages.Remove(existingMessage);
		_ = await dataContext.SaveChangesAsync(cancellationToken);

		return Result.Success();
	}

	/// <inheritdoc />
	public async Task<Result> RemoveBatch(List<Guid> messageIdList, CancellationToken cancellationToken)
	{
		_ = await dataContext.Messages
			.Where(x => messageIdList.Contains(x.Id))
			.ExecuteDeleteAsync(cancellationToken);

		return Result.Success();
	}
}