using e_suite.API.Common;
using e_suite.API.Common.models;
using e_suite.Utilities.Pagination;
using eSuite.API.security;
using eSuite.API.Utilities;
using eSuite.Core.MailService;
using eSuite.Core.Miscellaneous;
using eSuite.Core.Security;
using Microsoft.AspNetCore.Mvc;

namespace eSuite.API.Controllers;

/// <summary>
/// Mail templates are used when preparing emails that are sent by the system
/// </summary>
[Route("api/[controller]")]
public class MailTemplatesController : ESuiteControllerBase
{
    private readonly IMailTemplateManager _mailTemplateManager;

    /// <summary>
    /// Constructor for MailTemplate controller
    /// </summary>
    /// <param name="mailTemplateManager"></param>
    public MailTemplatesController(IMailTemplateManager mailTemplateManager)
    {
        _mailTemplateManager = mailTemplateManager;
    }

    /// <summary>
    /// Retrieve a list of the mail templates
    /// </summary>
    /// <param name="paging"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    [Route("types")]
    [HttpGet]
    [AccessKey(SecurityAccess.Everyone)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<IActionResult> GetMailTemplateTypes(
        [FromQuery] Paging paging,
        CancellationToken cancellationToken = default!
    )
    {
        var result = await _mailTemplateManager.GetMailTemplateTypes(paging, cancellationToken);
        return Ok(result);
    }

    /// <summary>
    /// Return the details for a given mail template. It will either return the domain specific version of the template, or the master copy as used by Sun.
    /// </summary>
    /// <param name="domain"></param>
    /// <param name="mailType"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    [Route("template")]
    [HttpGet]
    [AccessKey(SecurityAccess.Everyone)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<IActionResult> GetMailTemplate(
        [FromQuery] GeneralIdRef domain,
        MailType mailType,
        CancellationToken cancellationToken = default!
    )
    {
        var result = await _mailTemplateManager.GetMailTemplate(domain, mailType, cancellationToken);
        return Ok(result);
    }

    /// <summary>
    /// Save a mail template to the system to use by that domain.
    /// </summary>
    /// <param name="mailTemplate"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    [Route("template")]
    [HttpPost]
    [AccessKey(SecurityAccess.Everyone)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<IActionResult> PostMailTemplate(
        [FromBody] PostMailTemplate mailTemplate,
        CancellationToken cancellationToken = default!
    )
    {
        await _mailTemplateManager.PostMailTemplate(mailTemplate, AuditUserDetails, cancellationToken);
        return Ok();
    }
}