using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Hims.Api.Controllers
{
    using Hims.Api.Models;
    using Hims.Api.Utilities;
    using Hims.Domain.Repositories.UnitOfWork;
    using Hims.Domain.Services;
    using Hims.Shared.DataFilters;
    using Hims.Shared.EntityModels;
    using Hims.Shared.Library.Enums;
    using Hims.Shared.UserModels;
    using Hims.Shared.UserModels.Common;
    using Microsoft.AspNetCore.Authorization;
    using Npgsql;
    using Shared.UserModels.Filters;

    /// <inheritdoc />
    [Authorize]
    [Route("api/doctor-appointment-notice")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class DoctorAppointmentNoticeController : BaseController
    {
        public readonly IDoctorAppointmentNoticeService doctorAppointmentNoticeService;

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

        /// <summary>
        /// The unit of work.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

        public DoctorAppointmentNoticeController(IDoctorAppointmentNoticeService doctorAppointmentNoticeService, IAuditLogService auditLogServices, IUnitOfWork unitOfWork)
        {
            this.doctorAppointmentNoticeService = doctorAppointmentNoticeService;
            this.auditLogServices = auditLogServices;
            this.unitOfWork = unitOfWork;
        }

        [AllowAnonymous]
        [HttpPost]
        [Route("fetch")]
        [ProducesResponseType(typeof(List<DoctorAppointmentNoticeModel>), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchAsync([FromBody] DoctorAppointmentNoticeModel model)
        {
            model = (DoctorAppointmentNoticeModel)EmptyFilter.Handler(model);
            var response = await this.doctorAppointmentNoticeService.FetchAsync(model);
            return response == null ? this.ServerError() : this.Success(response);
        }

        /// <summary>
        /// The delete  Doctor Appointment Notice.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 -  Doctor Appointment Notice deleted successfully.
        /// - 409 - Doctor Appointment Notice 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] DoctorAppointmentNoticeModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model = (DoctorAppointmentNoticeModel)EmptyFilter.Handler(model);
                model.LocationId = Convert.ToInt32(header.LocationId);
                var foundDeletingItem = await this.unitOfWork.DoctorAppointmentNotices.FindAsync(m => m.DoctorAppointmentNoticeId == model.DoctorAppointmentNoticeId);
                var response = await this.doctorAppointmentNoticeService.DeleteAsync(model.DoctorAppointmentNoticeId);                
                var providerName = await this.unitOfWork.Providers.FindAsync(p => p.ProviderId == foundDeletingItem.ProviderId);
                var locationName = await this.unitOfWork.Locations.FindAsync(l => l.LocationId == foundDeletingItem.LocationId);
                if (response == 0)
                {
                    return this.ServerError();
                }

                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.ModifiedBy,
                    LogTypeId = (int)LogTypes.DoctorAppointmentNotice,
                    LogFrom = (int)AccountType.Administrator,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    LogDescription = $" { model.ModifiedByName } has deleted Doctor Appointment Notice - {foundDeletingItem.Description} for the Doctor {providerName.FullName} to the location {locationName.Name} on { DateTime.UtcNow.AddMinutes(330) }",
                    LocationId = model.LocationId
                };
                await this.auditLogServices.LogAsync(auditLogModel);

                return this.Success(" Doctor Appointment Notice has been deleted successfully.");
            }
            catch (NpgsqlException exception)
            {
                if (exception.Message.Contains("violates foreign key constraint"))
                {
                    return this.Conflict(" Doctor Appointment Notice can't be deleted. Please contact Administrator.");
                }

                return this.ServerError();
            }
        }


        /// <summary>
        /// The delete  Doctor Appointment Notice.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 -  Doctor Appointment Notice deleted successfully.
        /// - 409 -  Doctor Appointment Notice can not be deleted.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("modify-status")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ModifyStatusAsync([FromBody] DoctorAppointmentNoticeModel model, [FromHeader] LocationHeader header)
        {

            model = (DoctorAppointmentNoticeModel)EmptyFilter.Handler(model);

            var response = await this.doctorAppointmentNoticeService.ModifyStatusAsync(model); 
            var foundDeletingItem = await this.unitOfWork.DoctorAppointmentNotices.FindAsync(m => m.DoctorAppointmentNoticeId == model.DoctorAppointmentNoticeId);
            var providerName = await this.unitOfWork.Providers.FindAsync(p => p.ProviderId == model.ProviderId);
            var locationName = await this.unitOfWork.Locations.FindAsync(l => l.LocationId == model.LocationId);
            if (response == 0)
            {
                return this.ServerError();
            }

            var auditLog = new AuditLogModel
            {
                AccountId = model.CreatedBy,
                LogTypeId = (int)LogTypes.DoctorAppointmentNotice,
                LogDate = DateTime.Now,
                LogFrom = (short)model.LoginRoleId,
                LogDescription = $"{model.CreatedByName} has modified<b>Doctor Appointment Notice</b> of <strong>{foundDeletingItem.Description}</strong> for the Doctor <strong>{providerName.FullName}</strong> to the Location <strong>{locationName.Name}</strong> successfully.",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLog);

            return this.Success("Doctor Appointment Notice has been updated the status.");
        }

        [AllowAnonymous]
        [HttpPost]
        [Route("add")]

        public async Task<ActionResult> Insert([FromBody] DoctorAppointmentNoticeModel model)
        {
            model = (DoctorAppointmentNoticeModel)EmptyFilter.Handler(model);
            try
            {

                var response = await this.doctorAppointmentNoticeService.InsertAsync(model);
                switch (response)
                {
                    case -1:
                        return this.Conflict(" Doctor Appointment Notice has already been exists with us in between dates.");
                    case 0:
                        return this.ServerError();
                }
                var providerName = await this.unitOfWork.Providers.FindAsync(p => p.ProviderId == model.ProviderId);
                var locationName = await this.unitOfWork.Locations.FindAsync(l => l.LocationId == model.LocationId);
                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.ModifiedBy,
                    LogTypeId = (int)LogTypes.DoctorAppointmentNotice,
                    LogFrom = (int)AccountType.Administrator,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    LogDescription = $" { model.ModifiedByName } has Added Doctor Appointment Notice - {model.Description} for the Doctor {providerName.FullName} to the location {locationName} on { DateTime.UtcNow.AddMinutes(330) }",
                    LocationId = model.LocationId
                };
                await this.auditLogServices.LogAsync(auditLogModel);

                return this.Success(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });


            }
            catch (Exception e)
            {

                return this.Conflict(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = e.Message
                });
            }



        }
        /// <summary>
        /// The update charge.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - charge updated successfully.
        /// - 409 - Charge already exist.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPut]
        [Route("edit")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> EditAsync([FromBody] DoctorAppointmentNoticeModel model)
        {
            try
            {
                model = (DoctorAppointmentNoticeModel)EmptyFilter.Handler(model);
                //Console.WriteLine(model);


                var response = await this.doctorAppointmentNoticeService.UpdateAsync(model);
                var foundDeletingItem = await this.unitOfWork.DoctorAppointmentNotices.FindAsync(m => m.DoctorAppointmentNoticeId == model.DoctorAppointmentNoticeId);
                var providerName = await this.unitOfWork.Providers.FindAsync(p => p.ProviderId == model.ProviderId);
                var locationName = await this.unitOfWork.Locations.FindAsync(l => l.LocationId == model.LocationId);
                switch (response)
                {
                    case -1:
                        return this.Conflict(" Doctor Appointment Notice has already been exists with us in between dates.");
                    case 0:
                        return this.ServerError();
                }

                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.ModifiedBy,
                    LogTypeId = (int)LogTypes.DoctorAppointmentNotice,
                    LogFrom = (int)AccountType.Administrator,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    LogDescription = $" { model.ModifiedByName } has Updated Doctor Appointment Notice - {model.Description} for the Doctor {providerName.FullName} to the location {locationName.Name} on { DateTime.UtcNow.AddMinutes(330) }",
                    LocationId = model.LocationId
                };
                await this.auditLogServices.LogAsync(auditLogModel);

                return this.Success(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });

            }

            catch (Exception e)
            {
                return this.Conflict(e.Message);
            }

        }
    }
}
