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

namespace OmsorgCore.Infrastructure.Repositories;

public class ContractRepository : IContractRepository
{
    private readonly OmsorgCoreDbContext _db;

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

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

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

    public async Task<(IReadOnlyList<Contract> Items, int TotalCount)> GetPagedAsync(
        string? search,
        string? status,
        Guid? employeeId,
        Guid? facilityId,
        int page,
        int pageSize,
        CancellationToken cancellationToken = default)
    {
        var query = _db.Contracts.AsNoTracking().Where(c => !c.IsDeleted);

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

        if (!string.IsNullOrWhiteSpace(status))
        {
            query = query.Where(c => c.Status == status);
        }

        if (employeeId.HasValue)
        {
            query = query.Where(c => c.EmployeeId == employeeId.Value);
        }

        if (facilityId.HasValue)
        {
            query = query.Where(c => c.FacilityId == facilityId.Value);
        }

        var totalCount = await query.CountAsync(cancellationToken);

        var items = await query
            .OrderBy(c => c.StartDate)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync(cancellationToken);

        return (items, totalCount);
    }

    public Task<Contract?> GetActiveForEmployeeCoveringRangeAsync(
        Guid employeeId,
        DateOnly startDate,
        DateOnly endDate,
        CancellationToken cancellationToken = default)
        => _db.Contracts
            .Where(c => !c.IsDeleted && c.EmployeeId == employeeId && c.Status != "Entwurf")
            .Where(c => c.StartDate <= startDate && (c.EndDate == null || c.EndDate >= endDate))
            .FirstOrDefaultAsync(cancellationToken);

    public async Task AddAsync(Contract contract, CancellationToken cancellationToken = default)
        => await _db.Contracts.AddAsync(contract, cancellationToken);

    public Task UpdateAsync(Contract contract, CancellationToken cancellationToken = default)
    {
        _db.Contracts.Update(contract);
        return Task.CompletedTask;
    }

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

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

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

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

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

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

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

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