package domain

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

// JSONMap is a custom type for handling map[string]any with PostgreSQL JSONB
type JSONMap map[string]any

// Value implements the driver.Valuer interface
func (m JSONMap) Value() (driver.Value, error) {
	if m == nil {
		return nil, nil
	}
	ba, err := json.Marshal(m)
	return string(ba), err
}

// Scan implements the sql.Scanner interface
func (m *JSONMap) Scan(value any) error {
	if value == nil {
		*m = make(JSONMap)
		return nil
	}
	var bytes []byte
	switch v := value.(type) {
	case []byte:
		bytes = v
	case string:
		bytes = []byte(v)
	default:
		return errors.New(fmt.Sprintf("failed to scan JSONMap: %v", value))
	}

	result := make(JSONMap)
	err := json.Unmarshal(bytes, &result)
	*m = result
	return err
}
