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 PatientDeviceDetailsServices : IPatientDeviceDetailsService
    {
        /// <summary>
        /// The unit of work.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

        /// <inheritdoc cref="IPatientDeviceDetailsService"/> />
        public PatientDeviceDetailsServices(IUnitOfWork unitOfWork) => this.unitOfWork = unitOfWork;

        /// <inheritdoc />
        public async Task<IEnumerable<PatientDeviceDetailsModel>> 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<PatientDeviceDetailsModel>(query);
            return records;
        }

        /// <inheritdoc />
        public Task<int> InsertAsync(PatientDeviceDetailsModel model)
        {
            var patientDeviceDetails = new PatientDeviceDetails
            {
                PatientId = model.PatientId ?? 0,
                Duration = model.Duration,
                Reason = model.Reason,
                CallEndedAt = model.CallEndedAt,
                CallLiftedAt = model.CallLiftedAt,
                CallStartedAt = model.CallStartedAt,
                CallerId = model.CallerId,
                IsWebcamOn = model.IsWebcamOn,
                IsMicOn = model.IsMicOn,
                RingedAt = model.RingedAt,
                Status = model.Status
            };

            return this.unitOfWork.PatientDeviceDetails.InsertAsync(patientDeviceDetails);
        }
    }
}