using Managing.Application.Abstractions;
using Managing.Application.Abstractions.Services;
using Managing.Domain.Workflows;
using Managing.Domain.Workflows.Synthetics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Managing.Api.Controllers
{
    /// <summary>
    /// Controller for managing workflows, including creating, retrieving, and deleting workflows.
    /// Requires authorization for access.
    /// </summary>
    [Authorize]
    public class WorkflowController : BaseController
    {
        private readonly IWorkflowService _workflowService;

        /// <summary>
        /// Initializes a new instance of the <see cref="WorkflowController"/> class.
        /// </summary>
        /// <param name="WorkflowService">Service for managing workflows.</param>
        /// <param name="userService">Service for user-related operations.</param>
        public WorkflowController(IWorkflowService WorkflowService, IUserService userService) : base(userService)
        {
            _workflowService = WorkflowService;
        }

        /// <summary>
        /// Creates a new workflow or updates an existing one based on the provided workflow request.
        /// </summary>
        /// <param name="workflowRequest">The workflow request containing the details of the workflow to be created or updated.</param>
        /// <returns>The created or updated workflow.</returns>
        [HttpPost]
        public async Task<ActionResult<Workflow>> PostWorkflow([ModelBinder]SyntheticWorkflow workflowRequest)
        {
            return Ok(await _workflowService.InsertOrUpdateWorkflow(workflowRequest));
        }

        /// <summary>
        /// Retrieves all workflows.
        /// </summary>
        /// <returns>A list of all workflows.</returns>
        [HttpGet]
        public ActionResult<IEnumerable<SyntheticWorkflow>> GetWorkflows()
        {
            return Ok(_workflowService.GetWorkflows());
        }

        /// <summary>
        /// Retrieves all available flows.
        /// </summary>
        /// <returns>A list of all available flows.</returns>
        [HttpGet]
        [Route("flows")]
        public async Task<ActionResult<IEnumerable<IFlow>>> GetAvailableFlows()
        {
              return Ok(await _workflowService.GetAvailableFlows());
        }

        /// <summary>
        /// Deletes a workflow by name.
        /// </summary>
        /// <param name="name">The name of the workflow to delete.</param>
        /// <returns>An ActionResult indicating the outcome of the operation.</returns>
        [HttpDelete]
        public ActionResult DeleteWorkflow(string name)
        {
            return Ok(_workflowService.DeleteWorkflow(name));
        }
    }
}