// src/ClaudeDo.Data/Repositories/PrimeScheduleRepository.cs
using ClaudeDo.Data.Models;
using Microsoft.EntityFrameworkCore;

namespace ClaudeDo.Data.Repositories;

public sealed class PrimeScheduleRepository
{
    private readonly ClaudeDoDbContext _context;

    public PrimeScheduleRepository(ClaudeDoDbContext context) => _context = context;

    public async Task<IReadOnlyList<PrimeScheduleEntity>> ListAsync(CancellationToken ct = default)
    {
        var rows = await _context.PrimeSchedules.AsNoTracking().ToListAsync(ct);
        return rows.OrderBy(s => s.TimeOfDay).ToList();
    }

    public async Task<PrimeScheduleEntity?> GetAsync(Guid id, CancellationToken ct = default) =>
        await _context.PrimeSchedules.AsNoTracking().FirstOrDefaultAsync(s => s.Id == id, ct);

    public async Task UpsertAsync(PrimeScheduleEntity entity, CancellationToken ct = default)
    {
        var existing = await _context.PrimeSchedules.FirstOrDefaultAsync(s => s.Id == entity.Id, ct);
        if (existing is null)
        {
            _context.PrimeSchedules.Add(entity);
        }
        else
        {
            existing.Days = entity.Days;
            existing.TimeOfDay = entity.TimeOfDay;
            existing.Enabled = entity.Enabled;
            existing.PromptOverride = entity.PromptOverride;
            existing.Kind = entity.Kind;
        }
        await _context.SaveChangesAsync(ct);
    }

    public async Task DeleteAsync(Guid id, CancellationToken ct = default)
    {
        var row = await _context.PrimeSchedules.FirstOrDefaultAsync(s => s.Id == id, ct);
        if (row is null) return;
        _context.PrimeSchedules.Remove(row);
        await _context.SaveChangesAsync(ct);
    }

    public async Task UpdateLastRunAsync(Guid id, DateTimeOffset when, CancellationToken ct = default)
    {
        var row = await _context.PrimeSchedules.FirstOrDefaultAsync(s => s.Id == id, ct);
        if (row is null) return;
        row.LastRunAt = when;
        await _context.SaveChangesAsync(ct);
    }
}
