// Copyright 2023 schukai GmbH
// SPDX-License-Identifier: AGPL-3.0

package jobqueue

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
)

type JSONMap map[string]interface{}

func (m *JSONMap) Scan(value interface{}) error {
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New("Scan source is not []byte")
	}

	if err := json.Unmarshal(bytes, m); err != nil {
		return err
	}
	return nil
}

func (m JSONMap) Value() (driver.Value, error) {
	if m == nil {
		// Return NULL if the map is nil
		return nil, nil
	}

	bytes, err := json.Marshal(m)
	if err != nil {
		return nil, err
	}
	return bytes, nil
}