package syncstate

import (
	"encoding/json"
	"fmt"

	"codeberg.org/mapleopentech/monorepo/native/desktop/maplefile/internal/domain/syncstate"
	"codeberg.org/mapleopentech/monorepo/native/desktop/maplefile/pkg/storage"
)

const syncStateKey = "sync_state"

type repository struct {
	storage storage.Storage
}

// ProvideRepository creates a new syncstate repository for Wire
func ProvideRepository(storage storage.Storage) syncstate.Repository {
	return &repository{storage: storage}
}

func (r *repository) Get() (*syncstate.SyncState, error) {
	data, err := r.storage.Get(syncStateKey)
	if err != nil {
		return nil, fmt.Errorf("failed to get sync state: %w", err)
	}
	if data == nil {
		// Return empty sync state if none exists
		return syncstate.NewSyncState(), nil
	}

	var state syncstate.SyncState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, fmt.Errorf("failed to unmarshal sync state: %w", err)
	}

	return &state, nil
}

func (r *repository) Save(state *syncstate.SyncState) error {
	data, err := json.Marshal(state)
	if err != nil {
		return fmt.Errorf("failed to marshal sync state: %w", err)
	}

	if err := r.storage.Set(syncStateKey, data); err != nil {
		return fmt.Errorf("failed to save sync state: %w", err)
	}

	return nil
}

func (r *repository) Reset() error {
	if err := r.storage.Delete(syncStateKey); err != nil {
		return fmt.Errorf("failed to reset sync state: %w", err)
	}
	return nil
}
