using MemberCenter.Application.Abstractions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Text;

namespace MemberCenter.Web.Areas.Admin.Controllers;

[Area("Admin")]
[Authorize(Policy = "Admin")]
[Route("admin/subscriptions")]
public class SubscriptionsController : Controller
{
    private readonly ISubscriptionAdminService _subscriptionService;

    public SubscriptionsController(ISubscriptionAdminService subscriptionService)
    {
        _subscriptionService = subscriptionService;
    }

    [HttpGet("")]
    public async Task<IActionResult> Index()
    {
        var subscriptions = await _subscriptionService.ListAsync();
        return View(subscriptions);
    }

    [HttpGet("export")]
    public async Task<IActionResult> Export()
    {
        var subscriptions = await _subscriptionService.ListAsync();
        var sb = new StringBuilder();
        sb.AppendLine("id,list_id,email,status,created_at");
        foreach (var s in subscriptions)
        {
            sb.AppendLine($"{s.Id},{s.ListId},{s.Email},{s.Status},{s.CreatedAt:o}");
        }

        return File(Encoding.UTF8.GetBytes(sb.ToString()), "text/csv", "subscriptions.csv");
    }
}
