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

namespace OmsorgCore.Infrastructure.Repositories;

public class FacilityRepository : IFacilityRepository
{
    private readonly OmsorgCoreDbContext _db;

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

    public Task<Facility?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
        => _db.Facilities.FirstOrDefaultAsync(f => f.Id == id, cancellationToken);

    public async Task<IReadOnlyList<Facility>> GetAllAsync(CancellationToken cancellationToken = default)
        => await _db.Facilities.AsNoTracking().ToListAsync(cancellationToken);

    public async Task<(IReadOnlyList<Facility> Items, int TotalCount)> GetPagedAsync(
        string? search,
        string? crmStatus,
        bool followUpDueOnly,
        int page,
        int pageSize,
        CancellationToken cancellationToken = default)
    {
        var query = _db.Facilities.AsNoTracking().Where(f => !f.IsDeleted);

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

        if (!string.IsNullOrWhiteSpace(crmStatus))
        {
            query = query.Where(f => f.CrmStatus == crmStatus);
        }

        if (followUpDueOnly)
        {
            query = query.Where(f => f.FollowUpDueDate != null);
        }

        var totalCount = await query.CountAsync(cancellationToken);

        var orderedQuery = followUpDueOnly
            ? query.OrderBy(f => f.FollowUpDueDate)
            : query.OrderBy(f => f.Name);

        var items = await orderedQuery
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync(cancellationToken);

        return (items, totalCount);
    }

    public async Task AddAsync(Facility facility, CancellationToken cancellationToken = default)
        => await _db.Facilities.AddAsync(facility, cancellationToken);

    public Task UpdateAsync(Facility facility, CancellationToken cancellationToken = default)
    {
        _db.Facilities.Update(facility);
        return Task.CompletedTask;
    }

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

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

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

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

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

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

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

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