using MemberCenter.Application.Abstractions;
using MemberCenter.Application.Models.Newsletter;
using MemberCenter.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;

namespace MemberCenter.Infrastructure.Services;

public sealed class SubscriptionAdminService : ISubscriptionAdminService
{
    private readonly MemberCenterDbContext _dbContext;

    public SubscriptionAdminService(MemberCenterDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<IReadOnlyList<SubscriptionDto>> ListAsync(int take = 200)
    {
        var subscriptions = await _dbContext.NewsletterSubscriptions
            .OrderByDescending(s => s.CreatedAt)
            .Take(take)
            .ToListAsync();

        return subscriptions
            .Select(s => new SubscriptionDto(
                s.Id,
                s.ListId,
                s.Email,
                s.Status,
                s.Preferences.RootElement.Clone(),
                s.CreatedAt))
            .ToList();
    }
}
