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

namespace OmsorgCore.Infrastructure.Repositories;

/// <summary>
/// Verwendungsprüfung für die Liste "TimeEntryStatus" — wie "OrderStatus" eine echte
/// Fremdschlüsselbeziehung (<c>TimeEntry.StatusId</c>) plus mögliche Übergangsregeln.
/// </summary>
public class TimeEntryStatusValueListUsageChecker : IValueListUsageChecker
{
    private readonly OmsorgCoreDbContext _db;

    public string Key => "TimeEntryStatus";

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

    public async Task<IReadOnlyList<ValueListUsageEntry>> FindUsagesAsync(Guid itemId, string itemValue, CancellationToken cancellationToken = default)
    {
        var timeEntryUsages = await _db.TimeEntries.AsNoTracking()
            .Where(t => t.StatusId == itemId)
            .Select(t => new ValueListUsageEntry("TimeEntry", t.Id, $"Zeiterfassung {t.Id}"))
            .ToListAsync(cancellationToken);

        var transitionUsages = await _db.ValueListItemTransitions.AsNoTracking()
            .Where(t => t.FromItemId == itemId || t.ToItemId == itemId)
            .Select(t => new ValueListUsageEntry("TimeEntryStatusTransition", t.Id, $"Übergang {t.FromItem.Value} → {t.ToItem.Value}"))
            .ToListAsync(cancellationToken);

        return timeEntryUsages.Concat(transitionUsages).ToList();
    }
}
