package bootstrap

import (
	"fmt"
	"log/slog"

	"gorm.io/gorm"
)

const sanitizeLegacyUserMetadataSQL = `
update users
set metadata = metadata - 'hanmacFamily' - 'userType',
    updated_at = now()
where metadata ? 'hanmacFamily'
   or metadata ? 'userType'
`

// SanitizeLegacyUserMetadata removes legacy UI classification flags from Baron user metadata.
func SanitizeLegacyUserMetadata(db *gorm.DB) error {
	if db == nil {
		return fmt.Errorf("database is not configured")
	}
	if !db.Migrator().HasTable("users") {
		slog.Info("[Bootstrap] Legacy user metadata sanitize skipped because users table does not exist")
		return nil
	}

	result := db.Exec(sanitizeLegacyUserMetadataSQL)
	if result.Error != nil {
		return fmt.Errorf("sanitize legacy user metadata: %w", result.Error)
	}
	slog.Info("[Bootstrap] Legacy user metadata sanitized", "rowsAffected", result.RowsAffected)
	return nil
}
