using MemberCenter.Api.Authorization;
using MemberCenter.Api.Contracts;
using MemberCenter.Application.Abstractions;
using MemberCenter.Application.Constants;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace MemberCenter.Api.Controllers;

[ApiController]
[Route("admin/newsletter-lists")]
[Authorize(Policy = "Admin")]
[AdminPermission(AdminPermissions.NewsletterLists)]
public class AdminNewsletterListsController : ControllerBase
{
    private readonly INewsletterListService _listService;

    public AdminNewsletterListsController(INewsletterListService listService)
    {
        _listService = listService;
    }

    [HttpGet]
    [AdminPermission(AdminPermissions.NewsletterListsIndex)]
    public async Task<IActionResult> List()
    {
        var lists = await _listService.ListAsync();
        return Ok(lists);
    }

    [HttpPost]
    [AdminPermission(AdminPermissions.NewsletterListsCreate)]
    public async Task<IActionResult> Create([FromBody] NewsletterListRequest request)
    {
        var list = await _listService.CreateAsync(request.TenantId, request.Name, request.Status);
        return Created($"/admin/newsletter-lists/{list.Id}", list);
    }

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

        return Ok(list);
    }

    [HttpPut("{id:guid}")]
    [AdminPermission(AdminPermissions.NewsletterListsEdit)]
    public async Task<IActionResult> Update(Guid id, [FromBody] NewsletterListRequest request)
    {
        var list = await _listService.UpdateAsync(id, request.TenantId, request.Name, request.Status);
        if (list is null)
        {
            return NotFound();
        }
        return Ok(list);
    }

    [HttpDelete("{id:guid}")]
    [AdminPermission(AdminPermissions.NewsletterListsDelete)]
    public async Task<IActionResult> Delete(Guid id)
    {
        var deleted = await _listService.DeleteAsync(id);
        if (!deleted)
        {
            return NotFound();
        }
        return NoContent();
    }
}
