using Microsoft.EntityFrameworkCore;
using OmsorgCore.Application.Abstractions;
using OmsorgCore.Domain.Entities;
using OmsorgCore.Infrastructure.Persistence;

namespace OmsorgCore.Infrastructure.Repositories;

public class FacilityQualificationRateRepository : IFacilityQualificationRateRepository
{
    private readonly OmsorgCoreDbContext _db;

    public FacilityQualificationRateRepository(OmsorgCoreDbContext db)
    {
        _db = db;
    }

    public Task<FacilityQualificationRate?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
        => _db.FacilityQualificationRates.FirstOrDefaultAsync(r => r.Id == id, cancellationToken);

    public async Task<IReadOnlyList<FacilityQualificationRate>> GetByFacilityIdAsync(Guid facilityId, CancellationToken cancellationToken = default)
        => await _db.FacilityQualificationRates
            .AsNoTracking()
            .Where(r => r.FacilityId == facilityId)
            .OrderBy(r => r.Qualification)
            .ToListAsync(cancellationToken);

    public async Task AddAsync(FacilityQualificationRate rate, CancellationToken cancellationToken = default)
        => await _db.FacilityQualificationRates.AddAsync(rate, cancellationToken);

    public Task UpdateAsync(FacilityQualificationRate rate, CancellationToken cancellationToken = default)
    {
        _db.FacilityQualificationRates.Update(rate);
        return Task.CompletedTask;
    }

    public async Task<bool> SoftDeleteAsync(Guid id, CancellationToken cancellationToken = default)
    {
        var rate = await _db.FacilityQualificationRates.FirstOrDefaultAsync(r => r.Id == id, cancellationToken);
        if (rate is null)
        {
            return false;
        }

        rate.IsDeleted = true;
        rate.DeletedAt = DateTime.UtcNow;
        return true;
    }

    public async Task<IReadOnlyList<FacilityQualificationRate>> GetDeletedAsync(string? search, CancellationToken cancellationToken = default)
    {
        var query = _db.FacilityQualificationRates.IgnoreQueryFilters().AsNoTracking().Where(r => r.IsDeleted);

        if (!string.IsNullOrWhiteSpace(search))
        {
            var pattern = $"%{search.Trim()}%";
            query = query.Where(r => EF.Functions.ILike(r.Qualification, pattern));
        }

        return await query.OrderByDescending(r => r.DeletedAt).ToListAsync(cancellationToken);
    }

    public async Task<bool> RestoreAsync(Guid id, CancellationToken cancellationToken = default)
    {
        var rate = await _db.FacilityQualificationRates.IgnoreQueryFilters().FirstOrDefaultAsync(r => r.Id == id && r.IsDeleted, cancellationToken);
        if (rate is null)
        {
            return false;
        }

        rate.IsDeleted = false;
        rate.DeletedAt = null;
        return true;
    }

    public Task SaveChangesAsync(CancellationToken cancellationToken = default)
        => _db.SaveChangesAsync(cancellationToken);
}
