package mastersettings

import (
	"time"

	"gorm.io/gorm"

	"wucher/internal/shared/pkg/uuidv7"
)

type MasterSettings struct {
	ID          []byte     `gorm:"type:binary(16);primaryKey;column:id"`
	CompanyName string     `gorm:"type:varchar(255);not null;column:company_name"`
	Title       string     `gorm:"type:varchar(255);column:title"`
	Subtitle    string     `gorm:"type:varchar(255);column:subtitle"`
	LogoFileID  []byte     `gorm:"type:binary(16);column:logo_file_id"`
	LogoURL     *string    `gorm:"type:varchar(512);column:logo_url"`
	CoverFileID []byte     `gorm:"type:binary(16);column:cover_file_id"`
	CreatedAt   time.Time  `gorm:"column:created_at"`
	CreatedBy   []byte     `gorm:"type:binary(16);column:created_by"`
	UpdatedAt   time.Time  `gorm:"column:updated_at"`
	UpdatedBy   []byte     `gorm:"type:binary(16);column:updated_by"`
	DeletedAt   *time.Time `gorm:"column:deleted_at"`
	DeletedBy   []byte     `gorm:"type:binary(16);column:deleted_by"`
}

func (MasterSettings) TableName() string { return "master_settings" }

type MasterSettingValue struct {
	SettingKey  string    `gorm:"type:varchar(120);primaryKey;column:setting_key"`
	Value       string    `gorm:"type:text;not null;column:value"`
	IsEncrypted bool      `gorm:"type:tinyint(1);not null;default:0;column:is_encrypted"`
	CreatedAt   time.Time `gorm:"column:created_at"`
	CreatedBy   []byte    `gorm:"type:binary(16);column:created_by"`
	UpdatedAt   time.Time `gorm:"column:updated_at"`
	UpdatedBy   []byte    `gorm:"type:binary(16);column:updated_by"`
}

func (MasterSettingValue) TableName() string { return "master_setting_values" }

const (
	SettingMicrosoftEntraTenantID     = "MS_ENTRA_TENANT_ID"
	SettingMicrosoftEntraClientID     = "MS_ENTRA_CLIENT_ID"
	SettingMicrosoftEntraClientSecret = "MS_ENTRA_CLIENT_SECRET"
	SettingMicrosoftEntraRedirectURL  = "MS_ENTRA_REDIRECT_URL"
	SettingMicrosoftEntraAuthority    = "MS_ENTRA_AUTHORITY"
	SettingMicrosoftEntraScopes       = "MS_ENTRA_SCOPES"
	SettingAuthLoginEmailOTPEnabled   = "AUTH_LOGIN_EMAIL_OTP_ENABLED"
)

var MicrosoftEntraSettingKeys = []string{
	SettingMicrosoftEntraTenantID,
	SettingMicrosoftEntraClientID,
	SettingMicrosoftEntraClientSecret,
	SettingMicrosoftEntraRedirectURL,
	SettingMicrosoftEntraAuthority,
	SettingMicrosoftEntraScopes,
}

func (m *MasterSettings) BeforeCreate(tx *gorm.DB) error {
	if len(m.ID) == 0 {
		m.ID = uuidv7.MustBytes()
	}
	return nil
}
