using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;

namespace ZB.MOM.WW.OtOpcUa.Admin.Services;

/// <summary>
///     Fleet-wide external-ID reservation inspector + FleetAdmin-only release flow per
///     <c>admin-ui.md §"Release an external-ID reservation"</c>. Release is audit-logged
///     (<see cref="ConfigAuditLog"/>) via <c>sp_ReleaseExternalIdReservation</c>.
/// </summary>
public sealed class ReservationService(OtOpcUaConfigDbContext db)
{
    public Task<List<ExternalIdReservation>> ListActiveAsync(CancellationToken ct) =>
        db.ExternalIdReservations.AsNoTracking()
            .Where(r => r.ReleasedAt == null)
            .OrderBy(r => r.Kind).ThenBy(r => r.Value)
            .ToListAsync(ct);

    public Task<List<ExternalIdReservation>> ListReleasedAsync(CancellationToken ct) =>
        db.ExternalIdReservations.AsNoTracking()
            .Where(r => r.ReleasedAt != null)
            .OrderByDescending(r => r.ReleasedAt)
            .Take(100)
            .ToListAsync(ct);

    public async Task ReleaseAsync(string kind, string value, string reason, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(reason))
            throw new ArgumentException("ReleaseReason is required (audit invariant)", nameof(reason));

        await db.Database.ExecuteSqlRawAsync(
            "EXEC dbo.sp_ReleaseExternalIdReservation @Kind = {0}, @Value = {1}, @ReleaseReason = {2}",
            [kind, value, reason],
            ct);
    }
}
