/*
  * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 *
 *
*/

package repocli

import (
	ocidigest "github.com/opencontainers/go-digest"
	"github.com/stretchr/testify/require"

	"bytes"
	"context"
	"fmt"
	"io"
	"testing"
	"time"
)

func TestDigest(t *testing.T) {
	place := "a/" //t.TempDir()
	fmt.Printf("Place: %s\n", place)
	var digstr string
	{
		payload := []byte("Hello, World")
		digobj := ocidigest.FromBytes(payload)
		require.NotNil(t, digobj)
		digstr = digobj.String()
		fmt.Printf("Digest: %s\n", digstr)
		fmt.Printf("Alg: %s\n", digobj.Algorithm())

		ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
		imager := NewEmptyImager(place)
		require.NotNil(t, imager)
		digest := fmt.Sprintf("%s:%s", digobj.Algorithm(), digobj.Encoded())
		size := int64(len(payload))
		reader := bytes.NewReader(payload)

		err := imager.WriteLayer(ctx, digest, size, reader)
		require.NoError(t, err)

		err = imager.writeIndex(ctx)
		require.NoError(t, err)

	}
	{
		imager, err := NewImagerFromPlace(place)
		require.NoError(t, err)
		require.NotNil(t, imager)

		ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
		exist, err := imager.ReadLayer(ctx, digstr, io.Discard)
		require.NoError(t, err)
		require.True(t, exist)

	}
}
