namespace Hims.Infrastructure.Services
{
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Dapper;
    using Domain.Entities;
    using Domain.Repositories.UnitOfWork;
    using Domain.Services;
    using Shared.EntityModels;

    /// <inheritdoc />
    public class DoctorDeviceDetailsServices : IDoctorDeviceDetailsService
    {
        /// <summary>
        /// The unit of work.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

        /// <summary>
        /// Initializes a new instance of the <see cref="DoctorDeviceDetailsServices"/> class.
        /// </summary>
        /// <param name="unitOfWork">
        /// The unit of work.
        /// </param>
        public DoctorDeviceDetailsServices(IUnitOfWork unitOfWork) => this.unitOfWork = unitOfWork;

        /// <inheritdoc />
        public async Task<IEnumerable<DoctorDeviceDetailsModel>> FetchAsync(int appointmentId)
        {
            var where = $@"WHERE 1 = 1";

            if (appointmentId > 0)
            {
                where = $@"WHERE a.""AppointmentId"" = {appointmentId}";
            }

            var query = $@"SELECT
	                                v.*,
	                                a.""AppointmentDate"",
	                                a.""AppointmentTime"",
	                                p.""FullName"" AS ""DoctorFullName"",
	                                pa.""FullName"" AS ""PatientFullName""
                                FROM
	                                ""VideoCallHistory"" v
	                                LEFT JOIN ""Appointment"" A ON A.""AppointmentId"" = v.""AppointmentId""
	                                LEFT JOIN ""Provider"" P ON P.""ProviderId"" = A.""ProviderId""
	                                LEFT JOIN ""Patient"" pa ON pa.""PatientId"" = A.""PatientId""

	                                {where} ORDER BY v.""VideoCallHistoryId"" desc LIMIT 10";
            var records = await this.unitOfWork.Current.QueryAsync<DoctorDeviceDetailsModel>(query);
            return records;
        }

        /// <inheritdoc />
        public Task<int> InsertAsync(DoctorDeviceDetailsModel model)
        {
            var doctorDeviceDetails = new DoctorDeviceDetails
            {
                AppointmentId = model.AppointmentId ?? 0,
                Duration = model.Duration,
                Reason = model.Reason,
                CallEndedAt = model.CallEndedAt,
                CallLiftedAt = model.CallLiftedAt,
                CallStartedAt = model.CallStartedAt,
                CallerId = model.CallerId,
                IsWebcamOn = model.IsWebcamOn ?? false,
                IsMicOn = model.IsMicOn ?? false,
                RingedAt = model.RingedAt,
                Status = model.Status
            };

            return this.unitOfWork.DoctorDeviceDetails.InsertAsync(doctorDeviceDetails);
        }
    }
}