namespace JSMR.Worker.Services;

public sealed class FileCheckpointStore : ICheckpointStore
{
    private readonly string _root = Path.Combine(AppContext.BaseDirectory, "State");

    public FileCheckpointStore() => Directory.CreateDirectory(_root);

    public Task<int?> GetLastPageAsync(string locale, CancellationToken ct)
    {
        string path = Path.Combine(_root, $"scan.{locale}.page");
        if (!File.Exists(path))
            return Task.FromResult<int?>(null);

        if (int.TryParse(File.ReadAllText(path).Trim(), out var n))
            return Task.FromResult<int?>(n);

        return Task.FromResult<int?>(null);
    }

    public Task SaveLastPageAsync(string locale, int page, CancellationToken ct)
    {
        string path = Path.Combine(_root, $"scan.{locale}.page");
        File.WriteAllText(path, page.ToString());

        return Task.CompletedTask;
    }
}