using MongoDB.Bson.Serialization.Attributes;
using StellaOps.Feedser.Core.Jobs;

namespace StellaOps.Feedser.Storage.Mongo;

[BsonIgnoreExtraElements]
public sealed class JobLeaseDocument
{
    [BsonId]
    public string Key { get; set; } = string.Empty;

    [BsonElement("holder")]
    public string Holder { get; set; } = string.Empty;

    [BsonElement("acquiredAt")]
    public DateTime AcquiredAt { get; set; }

    [BsonElement("heartbeatAt")]
    public DateTime HeartbeatAt { get; set; }

    [BsonElement("leaseMs")]
    public long LeaseMs { get; set; }

    [BsonElement("ttlAt")]
    public DateTime TtlAt { get; set; }
}

internal static class JobLeaseDocumentExtensions
{
    public static JobLease ToLease(this JobLeaseDocument document)
        => new(
            document.Key,
            document.Holder,
            DateTime.SpecifyKind(document.AcquiredAt, DateTimeKind.Utc),
            DateTime.SpecifyKind(document.HeartbeatAt, DateTimeKind.Utc),
            TimeSpan.FromMilliseconds(document.LeaseMs),
            DateTime.SpecifyKind(document.TtlAt, DateTimeKind.Utc));
}
