// TODO: Unify function names

// Storage is the handler for cache and db access
// It handles storing various data in the database as well as caching that data
// Said data includes notes, accounts, metadata about media files, servers and similar
package storage

import (
	"errors"

	"github.com/rs/zerolog/log"
	"gitlab.com/mstarongitlab/linstrom/storage/cache"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

// Storage is responsible for all database, cache and media related actions
// and serves as the lowest layer of the cake
type Storage struct {
	db    *gorm.DB
	cache *cache.Cache
}

var ErrInvalidData = errors.New("invalid data")

func NewStorage(dbUrl string, cache *cache.Cache) (*Storage, error) {
	db, err := gorm.Open(postgres.Open(dbUrl), &gorm.Config{
		Logger: newGormLogger(log.Logger),
	})
	if err != nil {
		return nil, err
	}
	err = db.AutoMigrate(
		MediaMetadata{},
		Account{},
		RemoteServer{},
		Note{},
		Role{},
		PasskeySession{},
		InboundJob{},
		OutboundJob{},
	)
	if err != nil {
		return nil, err
	}

	return &Storage{db, cache}, nil
}
