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

namespace OmsorgCore.Infrastructure.Repositories;

public class DocumentRepository : IDocumentRepository
{
    private readonly OmsorgCoreDbContext _db;

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

    public Task<Document?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
        => _db.Documents.Include(d => d.UploadedByUser).FirstOrDefaultAsync(d => d.Id == id, cancellationToken);

    public async Task<IReadOnlyList<Document>> GetByEntityAsync(string entityType, Guid entityId, CancellationToken cancellationToken = default)
        => await _db.Documents.AsNoTracking()
            .Include(d => d.UploadedByUser)
            .Where(d => d.EntityType == entityType && d.EntityId == entityId)
            .OrderByDescending(d => d.CreatedAt)
            .ToListAsync(cancellationToken);

    public async Task AddAsync(Document document, CancellationToken cancellationToken = default)
        => await _db.Documents.AddAsync(document, cancellationToken);

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

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

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

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

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

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

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

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