package util

import (
	"sync"
)

type FileDB[T any] struct {
	Path string
	mu   sync.Mutex
}

func (db *FileDB[T]) Do(fn func(*T) error) error {
	db.mu.Lock()
	defer db.mu.Unlock()

	d := new(T)
	err := ReadJSONFile(db.Path, d)
	if err != nil {
		panic(err)
	}
	err = fn(d)
	if err != nil {
		return err
	}
	err = WriteJSONFile(db.Path, d)
	if err != nil {
		panic(err)
	}
	return nil
}
