package models

import "odoo-go/pkg/orm"

// initIrConfigParameter registers ir.config_parameter — System parameters.
// Mirrors: odoo/addons/base/models/ir_config_parameter.py class IrConfigParameter
//
// Key/value store for system-wide configuration.
// Examples: web.base.url, database.uuid, mail.catchall.domain
func initIrConfigParameter() {
	m := orm.NewModel("ir.config_parameter", orm.ModelOpts{
		Description: "System Parameter",
		Order:       "key",
		RecName:     "key",
	})

	m.AddFields(
		orm.Char("key", orm.FieldOpts{String: "Key", Required: true, Index: true}),
		orm.Text("value", orm.FieldOpts{String: "Value", Required: true}),
	)

	// get_param: returns the value for a key, or default.
	// Mirrors: odoo/addons/base/models/ir_config_parameter.py IrConfigParameter.get_param()
	m.RegisterMethod("get_param", func(rs *orm.Recordset, args ...interface{}) (interface{}, error) {
		if len(args) == 0 {
			return "", nil
		}
		key, _ := args[0].(string)
		defaultVal := ""
		if len(args) > 1 {
			defaultVal, _ = args[1].(string)
		}
		env := rs.Env()
		var value string
		err := env.Tx().QueryRow(env.Ctx(),
			`SELECT value FROM ir_config_parameter WHERE key = $1`, key).Scan(&value)
		if err != nil {
			return defaultVal, nil
		}
		return value, nil
	})

	// set_param: sets the value for a key (upsert).
	// Mirrors: odoo/addons/base/models/ir_config_parameter.py IrConfigParameter.set_param()
	m.RegisterMethod("set_param", func(rs *orm.Recordset, args ...interface{}) (interface{}, error) {
		if len(args) < 2 {
			return false, nil
		}
		key, _ := args[0].(string)
		value, _ := args[1].(string)
		env := rs.Env()
		_, err := env.Tx().Exec(env.Ctx(),
			`INSERT INTO ir_config_parameter (key, value) VALUES ($1, $2)
			 ON CONFLICT (key) DO UPDATE SET value = $2`, key, value)
		if err != nil {
			return false, err
		}
		return true, nil
	})
}
