using OmsorgCore.Application.Abstractions;
using OmsorgCore.Domain.Entities;

namespace OmsorgCore.Application.Services;

public class FacilityQualificationRateService : IFacilityQualificationRateService
{
    private readonly IFacilityQualificationRateRepository _facilityQualificationRateRepository;

    public FacilityQualificationRateService(IFacilityQualificationRateRepository facilityQualificationRateRepository)
    {
        _facilityQualificationRateRepository = facilityQualificationRateRepository;
    }

    public Task<IReadOnlyList<FacilityQualificationRate>> GetByFacilityIdAsync(Guid facilityId, CancellationToken cancellationToken = default)
        => _facilityQualificationRateRepository.GetByFacilityIdAsync(facilityId, cancellationToken);

    public Task<FacilityQualificationRate?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
        => _facilityQualificationRateRepository.GetByIdAsync(id, cancellationToken);

    public async Task<FacilityQualificationRate> CreateAsync(FacilityQualificationRate rate, CancellationToken cancellationToken = default)
    {
        await _facilityQualificationRateRepository.AddAsync(rate, cancellationToken);
        await _facilityQualificationRateRepository.SaveChangesAsync(cancellationToken);
        return rate;
    }

    public async Task<FacilityQualificationRate?> UpdateAsync(Guid id, FacilityQualificationRate updates, CancellationToken cancellationToken = default)
    {
        var rate = await _facilityQualificationRateRepository.GetByIdAsync(id, cancellationToken);
        if (rate is null)
        {
            return null;
        }

        rate.Qualification = updates.Qualification;
        rate.Rate = updates.Rate;
        rate.UpdatedAt = DateTime.UtcNow;

        await _facilityQualificationRateRepository.UpdateAsync(rate, cancellationToken);
        await _facilityQualificationRateRepository.SaveChangesAsync(cancellationToken);
        return rate;
    }

    public async Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default)
    {
        var deleted = await _facilityQualificationRateRepository.SoftDeleteAsync(id, cancellationToken);
        if (deleted)
        {
            await _facilityQualificationRateRepository.SaveChangesAsync(cancellationToken);
        }

        return deleted;
    }

    public Task<IReadOnlyList<FacilityQualificationRate>> GetDeletedAsync(string? search, CancellationToken cancellationToken = default)
        => _facilityQualificationRateRepository.GetDeletedAsync(search, cancellationToken);

    public async Task<bool> RestoreAsync(Guid id, CancellationToken cancellationToken = default)
    {
        var restored = await _facilityQualificationRateRepository.RestoreAsync(id, cancellationToken);
        if (restored)
        {
            await _facilityQualificationRateRepository.SaveChangesAsync(cancellationToken);
        }

        return restored;
    }
}
