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

namespace OmsorgCore.Infrastructure.Repositories;

public class FacilityContactRepository : IFacilityContactRepository
{
    private readonly OmsorgCoreDbContext _db;

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

    public Task<FacilityContact?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
        => _db.FacilityContacts.FirstOrDefaultAsync(c => c.Id == id, cancellationToken);

    public async Task<IReadOnlyList<FacilityContact>> GetByFacilityIdAsync(Guid facilityId, CancellationToken cancellationToken = default)
        => await _db.FacilityContacts
            .AsNoTracking()
            .Where(c => c.FacilityId == facilityId)
            .OrderBy(c => c.Name)
            .ToListAsync(cancellationToken);

    public async Task AddAsync(FacilityContact contact, CancellationToken cancellationToken = default)
        => await _db.FacilityContacts.AddAsync(contact, cancellationToken);

    public Task UpdateAsync(FacilityContact contact, CancellationToken cancellationToken = default)
    {
        _db.FacilityContacts.Update(contact);
        return Task.CompletedTask;
    }

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

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

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

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

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

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

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

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