package services

import (
	"crypto/sha256"
	"encoding/hex"
	"os"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestCalculateSHA256(t *testing.T) {
	service := &ConversionService{}

	dir := t.TempDir()
	testFile := filepath.Join(dir, "test.epub")

	content := "test content for hash calculation"
	err := os.WriteFile(testFile, []byte(content), 0644)
	require.NoError(t, err)

	hash, err := service.calculateSHA256(testFile)
	require.NoError(t, err)

	expectedHash := sha256.New()
	expectedHash.Write([]byte(content))
	expectedHashStr := hex.EncodeToString(expectedHash.Sum(nil))

	assert.Equal(t, expectedHashStr, hash)
	assert.Len(t, hash, 64)
}

func TestConvertEPUBToKEPUBCreatesCacheDir(t *testing.T) {
	cacheDir := filepath.Join(t.TempDir(), "cache", "kepub")
	_ = NewConversionService(nil, cacheDir)

	assert.NoFileExists(t, cacheDir, "Cache directory should not exist initially")

	err := os.MkdirAll(cacheDir, 0755)
	require.NoError(t, err, "Should be able to create cache directory")

	assert.DirExists(t, cacheDir, "Cache directory should exist after creation")
}

func TestConvertedKEPUBStructure(t *testing.T) {
	validHash := "abc123def456789abc123def456789abc123def456789abc123def456789abcd"
	result := &ConvertedKEPUB{
		Path:   "/path/to/book.kepub.epub",
		SHA256: validHash,
		Cached: false,
	}

	assert.NotEmpty(t, result.Path)
	assert.NotEmpty(t, result.SHA256)
	assert.False(t, result.Cached)
	assert.Len(t, result.SHA256, 64)
}

func TestConversionServiceDefaults(t *testing.T) {
	cacheDir := t.TempDir()
	service := NewConversionService(nil, cacheDir)

	assert.NotNil(t, service)
	assert.Equal(t, cacheDir, service.cacheDir)
	assert.Equal(t, "/usr/bin/kepubify", service.conversionTool)
	assert.Equal(t, int64(24*3600*1000000000), service.conversionCacheTTL.Nanoseconds(), "Default TTL field should be 24 hours")
	// cacheTTL() must reflect the same default when no registry is wired.
	assert.Equal(t, int64(24*3600*1000000000), service.cacheTTL().Nanoseconds(), "Default TTL accessor should return 24 hours")
}
