package orgpolicy

import (
	"context"
	"encoding/json"
	"strings"

	"github.com/jackc/pgx/v5"
)

// PublicAgendaPolicy is exposed to authenticated users (no API keys).
type PublicAgendaPolicy struct {
	DefaultThemeMode          string   `json:"default_theme_mode"`
	EnforceOrgTheme           bool     `json:"enforce_org_theme"`
	DefaultVideoProvider      string   `json:"default_video_provider"`
	EnforceOrgVideoProvider   bool     `json:"enforce_org_video_provider"`
	ConfiguredVideoProviders  []string `json:"configured_video_providers"`
}

func defaultAgendaPolicy() map[string]any {
	return map[string]any{
		"default_theme_mode":          "system",
		"enforce_org_theme":           false,
		"default_video_provider":      "ultimeet",
		"enforce_org_video_provider":  false,
		"video_provider_api_keys":     map[string]any{},
	}
}

func (l *Loader) PublicAgendaPolicy(ctx context.Context) (PublicAgendaPolicy, error) {
	var raw []byte
	err := l.db.QueryRow(ctx, `
		SELECT settings FROM org_settings WHERE id = $1
	`, orgSettingsSingletonID).Scan(&raw)
	if err != nil && err != pgx.ErrNoRows {
		return PublicAgendaPolicy{}, err
	}

	stored := map[string]any{}
	if len(raw) > 0 {
		if err := json.Unmarshal(raw, &stored); err != nil {
			return PublicAgendaPolicy{}, err
		}
	}

	agenda, _ := stored["agenda"].(map[string]any)
	if agenda == nil {
		agenda = defaultAgendaPolicy()
	}

	keys, _ := agenda["video_provider_api_keys"].(map[string]any)
	configured := []string{"ultimeet"}
	for _, provider := range []string{"google_meet", "zoom", "teams", "jitsi"} {
		if v, ok := keys[provider].(string); ok && strings.TrimSpace(v) != "" {
			configured = append(configured, provider)
		}
	}
	defaultProvider, _ := agenda["default_video_provider"].(string)
	if defaultProvider == "" {
		defaultProvider = "ultimeet"
	}
	themeMode, _ := agenda["default_theme_mode"].(string)
	if themeMode == "" {
		themeMode = "system"
	}

	return PublicAgendaPolicy{
		DefaultThemeMode:         themeMode,
		EnforceOrgTheme:          boolField(agenda, "enforce_org_theme"),
		DefaultVideoProvider:     defaultProvider,
		EnforceOrgVideoProvider:  boolField(agenda, "enforce_org_video_provider"),
		ConfiguredVideoProviders: configured,
	}, nil
}

func boolField(m map[string]any, key string) bool {
	v, ok := m[key].(bool)
	return ok && v
}
