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

namespace OmsorgCore.Infrastructure.Repositories;

public class TimeEntryRepository : ITimeEntryRepository
{
    private readonly OmsorgCoreDbContext _db;

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

    public Task<TimeEntry?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
        => _db.TimeEntries.Include(t => t.Employee).Include(t => t.Order).ThenInclude(o => o.Facility).Include(t => t.Status)
            .FirstOrDefaultAsync(t => t.Id == id, cancellationToken);

    public async Task<(IReadOnlyList<TimeEntry> Items, int TotalCount)> GetPagedAsync(
        Guid? statusId,
        Guid? employeeId,
        Guid? orderId,
        int page,
        int pageSize,
        CancellationToken cancellationToken = default,
        Guid? restrictToEmployeeId = null)
    {
        var query = _db.TimeEntries.AsNoTracking()
            .Include(t => t.Employee)
            .Include(t => t.Order).ThenInclude(o => o.Facility)
            .Include(t => t.Status)
            .Where(t => !t.IsDeleted);

        if (restrictToEmployeeId.HasValue)
        {
            query = query.Where(t => t.EmployeeId == restrictToEmployeeId.Value);
        }
        else if (employeeId.HasValue)
        {
            query = query.Where(t => t.EmployeeId == employeeId.Value);
        }

        if (orderId.HasValue)
        {
            query = query.Where(t => t.OrderId == orderId.Value);
        }

        if (statusId.HasValue)
        {
            query = query.Where(t => t.StatusId == statusId.Value);
        }

        var totalCount = await query.CountAsync(cancellationToken);

        var items = await query
            .OrderByDescending(t => t.CreatedAt)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync(cancellationToken);

        return (items, totalCount);
    }

    public async Task AddAsync(TimeEntry timeEntry, CancellationToken cancellationToken = default)
        => await _db.TimeEntries.AddAsync(timeEntry, cancellationToken);

    public Task UpdateAsync(TimeEntry timeEntry, CancellationToken cancellationToken = default)
    {
        _db.TimeEntries.Update(timeEntry);
        return Task.CompletedTask;
    }

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

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

    public async Task<IReadOnlyList<TimeEntry>> GetDeletedAsync(string? search, CancellationToken cancellationToken = default)
    {
        var query = _db.TimeEntries.IgnoreQueryFilters().AsNoTracking()
            .Include(t => t.Employee).Include(t => t.Order).Include(t => t.Status)
            .Where(t => t.IsDeleted);

        if (!string.IsNullOrWhiteSpace(search))
        {
            var pattern = $"%{search.Trim()}%";
            query = query.Where(t =>
                (t.Employee != null && (EF.Functions.ILike(t.Employee.FirstName, pattern) || EF.Functions.ILike(t.Employee.LastName, pattern))));
        }

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

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

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

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