using Nexus.Api.DTOs;

namespace Nexus.Api.Services;

/// <summary>
/// Compatibility adapter for the existing calendar API. Its data now comes
/// exclusively from the real OpenClaw cron control plane; disconnected or
/// unsupported Gateways return an empty list instead of fabricated jobs.
/// </summary>
public sealed class CalendarService(
    IOpenClawControlService openClaw) : ICalendarService
{
    public async Task<IReadOnlyList<CronJobEntry>> GetCronJobsAsync(
        CancellationToken ct = default)
    {
        var response = await openClaw.GetCronJobsAsync(200, ct);
        return response.Items
            .Select(job => new CronJobEntry(
                job.Id,
                job.Name,
                job.Schedule,
                job.LastRunAt?.ToString("O") ?? string.Empty,
                job.NextRunAt?.ToString("O") ?? string.Empty,
                job.Status))
            .ToArray();
    }

    public async Task<IReadOnlyList<UpcomingCronEntry>> GetUpcomingCronJobsAsync(
        CancellationToken ct = default)
    {
        var response = await openClaw.GetCronJobsAsync(200, ct);
        return response.Items
            .Where(job => job.Enabled && job.NextRunAt is not null)
            .OrderBy(job => job.NextRunAt)
            .Select(job => new UpcomingCronEntry(
                job.Id,
                job.Name,
                job.NextRunAt!.Value.ToString("O"),
                job.Schedule))
            .ToArray();
    }
}
