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

namespace MemberCenter.Web.Areas.Admin.Controllers;

[Area("Admin")]
[Authorize(Policy = "Admin")]
[Route("admin/newsletter-lists")]
public class NewsletterListsController : Controller
{
    private readonly INewsletterListService _listService;
    private readonly ITenantService _tenantService;

    public NewsletterListsController(INewsletterListService listService, ITenantService tenantService)
    {
        _listService = listService;
        _tenantService = tenantService;
    }

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

    [HttpGet("create")]
    public async Task<IActionResult> Create()
    {
        var tenants = await _tenantService.ListAsync();
        return View(new NewsletterListFormViewModel
        {
            Tenants = tenants
        });
    }

    [HttpPost("create")]
    public async Task<IActionResult> Create(NewsletterListFormViewModel model)
    {
        if (!ModelState.IsValid)
        {
            model.Tenants = await _tenantService.ListAsync();
            return View(model);
        }

        await _listService.CreateAsync(model.TenantId, model.Name, model.Status);
        return RedirectToAction("Index");
    }

    [HttpGet("edit/{id:guid}")]
    public async Task<IActionResult> Edit(Guid id)
    {
        var list = await _listService.GetAsync(id);
        if (list is null)
        {
            return NotFound();
        }

        var tenants = await _tenantService.ListAsync();
        return View(new NewsletterListFormViewModel
        {
            Id = list.Id,
            TenantId = list.TenantId,
            Name = list.Name,
            Status = list.Status,
            Tenants = tenants
        });
    }

    [HttpPost("edit/{id:guid}")]
    public async Task<IActionResult> Edit(Guid id, NewsletterListFormViewModel model)
    {
        if (!ModelState.IsValid)
        {
            model.Tenants = await _tenantService.ListAsync();
            return View(model);
        }

        var updated = await _listService.UpdateAsync(id, model.TenantId, model.Name, model.Status);
        if (updated is null)
        {
            return NotFound();
        }

        return RedirectToAction("Index");
    }

    [HttpPost("delete/{id:guid}")]
    public async Task<IActionResult> Delete(Guid id)
    {
        await _listService.DeleteAsync(id);
        return RedirectToAction("Index");
    }
}
