namespace Hims.Api.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Domain.Services;
    using Hims.Api.Models;
    using Hims.Shared.UserModels;
    using Hims.Shared.UserModels.Scan.ScanSubClassification;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.CodeAnalysis.CSharp;
    using Npgsql;
    using Shared.DataFilters;
    using Shared.EntityModels;
    using Shared.Library.Enums;
    using Shared.UserModels.Filters;
    using Utilities;

    /// <inheritdoc />
    [Authorize]
    [Route("api/scan-sub-classification")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class ScanSubClassification : BaseController
    {
        /// <summary>
        /// The coupon services.
        /// </summary>
        private readonly IScanSubClassificationService scanSubClassificationService;

        /// <summary>
        /// The scan service.
        /// </summary>
        private readonly IScanLogService scanLogService;

        /// <summary>
        /// The audit log services.
        /// </summary>
        private readonly IAuditLogService auditLogServices;


        /// <inheritdoc />
        public ScanSubClassification(IScanSubClassificationService scanSubClassificationService, IAuditLogService auditLogServices, IScanLogService scanLogService)
        {
            this.scanSubClassificationService = scanSubClassificationService;
            this.auditLogServices = auditLogServices;
            this.scanLogService = scanLogService;
        }



        /// <summary>
        /// The add scan classification.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - scan classification added successfully.
        /// - 409 - scan classification already exist.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("add")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> AddAsync([FromBody] InsertModel model, [FromHeader] LocationHeader header)
        {
            model = (InsertModel)EmptyFilter.Handler(model);
            //model.LocationId = Convert.ToInt32(header.LocationId);
            var response = await this.scanSubClassificationService.AddAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given Scan Sub Classification has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            foreach (var record in model.Details)
            {
                var scanLogModel = new ScanLogModel
                {
                    AccountId = model.CreatedBy,
                    ScanLogTypeId = (int)ScanLogTypes.ScanSubClassification,
                    LogFrom = (short)model.LoginRoleId,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    LocationId = Convert.ToInt32(header.LocationId),
                    LogDescription = $" {model.ModifiedByName} has Added Scan Sub Classification : <b>{record.ScanSubClassificationName}</b> Successfully.",
                };
                await this.scanLogService.LogAsync(scanLogModel);
            }
            return this.Success(response);
        }

        /// <summary>
        /// The add coupon.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Coupon added successfully.
        /// - 409 - Coupon already exist.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("update")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> UpdateAsync([FromBody] InsertModel model, [FromHeader] LocationHeader header)
        {
            model = (InsertModel)EmptyFilter.Handler(model);
            //model.LocationId = Convert.ToInt32(header.LocationId);
            var response = await this.scanSubClassificationService.UpdateAsync(model);
            switch (response)
            {
                case -1:
                    return this.Conflict("Given Scan Sub Classification has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            if (response > 0)
            {
                var scanLogModel = new ScanLogModel
                {
                    AccountId = model.CreatedBy,
                    ScanLogTypeId = (int)ScanLogTypes.ScanSubClassification,
                    LogFrom = (short)model.LoginRoleId,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    LocationId = Convert.ToInt32(header.LocationId),
                    LogDescription = $" {model.ModifiedByName} has Updated Scan Sub Classification : <b>{model.ScanSubClassificationName}</b> Successfully.",
                };
                await this.scanLogService.LogAsync(scanLogModel);
            }

            return this.Success("Scan Test has been updated successfully.");
        }

        /// <summary>
        /// The fetch classification async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("fetch")]
        public async Task<ActionResult> FetchAsync([FromBody] FetchModel model)
        {
            model = (FetchModel)EmptyFilter.Handler(model);
            var response = await this.scanSubClassificationService.FetchAll(model);
            return this.Success(response);
        }

        /// <summary>
        /// The fetch classification async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("fetch-details")]
        public async Task<ActionResult> FetchAltAsync([FromBody] FetchModel model)
        {
            model = (FetchModel)EmptyFilter.Handler(model);
            var response = await this.scanSubClassificationService.FetchAltAsync(model);
            return this.Success(response);
        }

        /// <summary>
        /// Modifies the Classification status asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("modify-scan-sub-classification-status")]
        public async Task<ActionResult> ModifySubClassificationStatusAsync([FromBody] InsertModel model, [FromHeader] LocationHeader header)
        {
            model = (InsertModel)EmptyFilter.Handler(model);
            var response = await this.scanSubClassificationService.ActivateOrDeactivateSubClassification(model);
            var scanLogModel = new ScanLogModel
            {
                AccountId = model.ModifiedBy,
                ScanLogTypeId = (int)ScanLogTypes.ScanSubClassification,
                LogFrom = (short)model.LoginRoleId,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LocationId = Convert.ToInt32(header.LocationId),
                LogDescription = response > 0 ? $" {model.ModifiedByName}</b> has {(model.Active == true ? "Activated" : "Deactivated")} Scan Sub Classification : <b>{model.ScanSubClassificationName}</b> successfully." : $" {model.ModifiedByName}</b> has tried to Deactivate the Scan Sub Classification : <b>{model.ScanSubClassificationName}</b> - Cannot Deactivate this subClassification as it is linked to a Test.",
            };
            await this.scanLogService.LogAsync(scanLogModel);

            return this.Success(response);

        }
        /// <summary>
        /// The delete specialization.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Specialization deleted successfully.
        /// - 409 - Specialization can not be deleted.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("delete")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> DeleteAsync([FromBody] InsertModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (InsertModel)EmptyFilter.Handler(model);
                var response = await this.scanSubClassificationService.DeleteAsync(model.ScanSubClassificationId);
                if (response == 0)
                {
                    return this.ServerError();
                }

                if (response > 0)
                {
                    var scanLogModel = new ScanLogModel
                    {
                        AccountId = model.ModifiedBy,
                        ScanLogTypeId = (int)ScanLogTypes.ScanSubClassification,
                        LogFrom = (short)model.LoginRoleId,
                        LogDate = DateTime.UtcNow.AddMinutes(330),
                        LocationId = Convert.ToInt32(header.LocationId),
                        LogDescription = $" {model.ModifiedByName} has Deleted Scan Sub Classification : <b>{model.ScanSubClassificationName}</b> Successfully.",
                    };
                    await this.scanLogService.LogAsync(scanLogModel);
                }

                return this.Success(response);
            }
            catch (NpgsqlException exception)
            {
                if (exception.Message.Contains("violates foreign key constraint"))
                {
                    return this.Conflict("Room can't be deleted. Please contact Administrator.");
                }

                return this.ServerError();
            }
        }
    }


}