using MemberCenter.Application.Abstractions;
using MemberCenter.Web.Models.Newsletter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace MemberCenter.Web.Controllers;

public class NewsletterController : Controller
{
    private readonly INewsletterService _newsletterService;

    public NewsletterController(INewsletterService newsletterService)
    {
        _newsletterService = newsletterService;
    }

    [HttpGet]
    [AllowAnonymous]
    public IActionResult Confirm(string token)
    {
        return View(new ConfirmViewModel { Token = token });
    }

    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Confirm(ConfirmViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var subscription = await _newsletterService.ConfirmAsync(model.Token);
        if (subscription is null)
        {
            ViewData["Result"] = "Invalid or expired token.";
            return View("ConfirmResult");
        }

        ViewData["Result"] = "Subscription activated.";
        return View("ConfirmResult");
    }

    [HttpGet]
    [AllowAnonymous]
    public IActionResult Unsubscribe(string token)
    {
        return View(new UnsubscribeViewModel { Token = token });
    }

    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Unsubscribe(UnsubscribeViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var subscription = await _newsletterService.UnsubscribeAsync(model.Token);
        if (subscription is null)
        {
            ViewData["Result"] = "Invalid token.";
            return View("UnsubscribeResult");
        }

        ViewData["Result"] = "Subscription canceled.";
        return View("UnsubscribeResult");
    }
}
