package models

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

	"gorm.io/gorm"
)

// PageElementConfig represents the visual variant configuration for a page element
type PageElementConfig struct {
	gorm.Model
	PageType     string         `gorm:"not null;index" json:"page_type"`        // e.g., "homepage", "about", "blog"
	ElementName  string         `gorm:"not null;index" json:"element_name"`     // e.g., "header", "hero", "news", "matches"
	Variant      string         `gorm:"not null" json:"variant"`                // e.g., "unified", "edge", "minimal", "modern"
	Visible      bool           `gorm:"default:true" json:"visible"`            // Whether element is shown on page
	DisplayOrder int            `gorm:"default:0" json:"display_order"`         // Order of element on page
	Settings     ElementSettings `gorm:"type:jsonb" json:"settings,omitempty"`  // Additional variant-specific settings
}

// ElementSettings is a map for storing additional settings
type ElementSettings map[string]interface{}

// TableName specifies the table name for the PageElementConfig model
func (PageElementConfig) TableName() string {
	return "page_element_configs"
}

// Scan implements the sql.Scanner interface for ElementSettings
func (es *ElementSettings) Scan(value interface{}) error {
	if value == nil {
		*es = make(ElementSettings)
		return nil
	}
	
	bytes, ok := value.([]byte)
	if !ok {
		return errors.New("type assertion to []byte failed")
	}
	
	return json.Unmarshal(bytes, es)
}

// Value implements the driver.Valuer interface for ElementSettings
func (es ElementSettings) Value() (driver.Value, error) {
	if es == nil {
		return nil, nil
	}
	return json.Marshal(es)
}
