package main

import (
	"encoding/json"
	"net/http"
	"os"

	"fn-registry/functions/infra"
)

type FeatureFlag struct {
	Enabled     bool   `json:"enabled"`
	Issue       string `json:"issue,omitempty"`
	Description string `json:"description"`
	Added       string `json:"added,omitempty"`
	EnabledAt   string `json:"enabled_at,omitempty"`
}

type FeatureFlags struct {
	Flags map[string]FeatureFlag `json:"flags"`
}

func (f FeatureFlags) Enabled(name string) bool {
	flag, ok := f.Flags[name]
	return ok && flag.Enabled
}

func loadFeatureFlags(path string) (FeatureFlags, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			return FeatureFlags{Flags: map[string]FeatureFlag{}}, nil
		}
		return FeatureFlags{}, err
	}
	var f FeatureFlags
	if err := json.Unmarshal(b, &f); err != nil {
		return FeatureFlags{}, err
	}
	if f.Flags == nil {
		f.Flags = map[string]FeatureFlag{}
	}
	return f, nil
}

// GET /api/flags → { "<name>": true/false, ... }
func handleListFlags(flags *FeatureFlags) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		out := make(map[string]bool, len(flags.Flags))
		for name, fl := range flags.Flags {
			out[name] = fl.Enabled
		}
		infra.HTTPJSONResponse(w, http.StatusOK, out)
	}
}
