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/tenants")]
[Authorize(Policy = "Admin")]
[AdminPermission(AdminPermissions.Tenants)]
public class AdminTenantsController : ControllerBase
{
    private readonly ITenantService _tenantService;

    public AdminTenantsController(ITenantService tenantService)
    {
        _tenantService = tenantService;
    }

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

    [HttpPost]
    [AdminPermission(AdminPermissions.TenantsCreate)]
    public async Task<IActionResult> Create([FromBody] TenantRequest request)
    {
        var tenant = await _tenantService.CreateAsync(request.Name, request.Domains, request.Status, request.SendEngineWebhookClientId);
        return Created($"/admin/tenants/{tenant.Id}", tenant);
    }

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

        return Ok(tenant);
    }

    [HttpPut("{id:guid}")]
    [AdminPermission(AdminPermissions.TenantsEdit)]
    public async Task<IActionResult> Update(Guid id, [FromBody] TenantRequest request)
    {
        var tenant = await _tenantService.UpdateAsync(id, request.Name, request.Domains, request.Status, request.SendEngineWebhookClientId);
        if (tenant is null)
        {
            return NotFound();
        }
        return Ok(tenant);
    }

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