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

namespace MemberCenter.Web.Areas.Admin.Controllers;

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

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

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

    [HttpGet("export")]
    [AdminPermission(AdminPermissions.SubscriptionsExport)]
    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");
    }
}
