package session

import (
	"encoding/json"

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

const sessionKey = "current_session"

type repository struct {
	storage storage.Storage
}

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

func (r *repository) Save(sess *session.Session) error {
	data, err := json.Marshal(sess)
	if err != nil {
		return err
	}
	return r.storage.Set(sessionKey, data)
}

func (r *repository) Get() (*session.Session, error) {
	data, err := r.storage.Get(sessionKey)
	if err != nil {
		return nil, err
	}
	if data == nil {
		return nil, nil
	}

	var sess session.Session
	if err := json.Unmarshal(data, &sess); err != nil {
		return nil, err
	}
	return &sess, nil
}

func (r *repository) Delete() error {
	return r.storage.Delete(sessionKey)
}

func (r *repository) Exists() (bool, error) {
	data, err := r.storage.Get(sessionKey)
	if err != nil {
		return false, err
	}
	return data != nil, nil
}
