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/tenants")]
public class TenantsController : Controller
{
    private readonly ITenantService _tenantService;

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

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

    [HttpGet("create")]
    public IActionResult Create()
    {
        return View(new TenantFormViewModel());
    }

    [HttpPost("create")]
    public async Task<IActionResult> Create(TenantFormViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        if (!TryParseWebhookClientId(model.SendEngineWebhookClientId, out var webhookClientId))
        {
            ModelState.AddModelError(nameof(model.SendEngineWebhookClientId), "Webhook client id must be a valid UUID.");
            return View(model);
        }

        var domains = model.Domains.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
        await _tenantService.CreateAsync(model.Name, domains, model.Status, webhookClientId);
        return RedirectToAction("Index");
    }

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

        return View(new TenantFormViewModel
        {
            Id = tenant.Id,
            Name = tenant.Name,
            Domains = string.Join(",", tenant.Domains),
            Status = tenant.Status,
            SendEngineWebhookClientId = tenant.SendEngineWebhookClientId?.ToString()
        });
    }

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

        if (!TryParseWebhookClientId(model.SendEngineWebhookClientId, out var webhookClientId))
        {
            ModelState.AddModelError(nameof(model.SendEngineWebhookClientId), "Webhook client id must be a valid UUID.");
            return View(model);
        }

        var domains = model.Domains.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
        var updated = await _tenantService.UpdateAsync(id, model.Name, domains, model.Status, webhookClientId);
        if (updated is null)
        {
            return NotFound();
        }

        return RedirectToAction("Index");
    }

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

    private static bool TryParseWebhookClientId(string? value, out Guid? webhookClientId)
    {
        webhookClientId = null;
        if (string.IsNullOrWhiteSpace(value))
        {
            return true;
        }

        if (!Guid.TryParse(value.Trim(), out var parsed))
        {
            return false;
        }

        webhookClientId = parsed;
        return true;
    }
}
