package integration

import paymentutil "kra/pkg/paymentkit"

func integrationField(key, label string, required, secret bool, fieldType string) IntegrationConfigField {
	if fieldType == "" {
		fieldType = "text"
	}
	return IntegrationConfigField{Key: key, Label: label, Required: required, Secret: secret, Type: fieldType}
}

func integrationSelect(key, label string, required bool, values ...string) IntegrationConfigField {
	options := make([]IntegrationConfigOption, 0, len(values))
	for _, value := range values {
		options = append(options, IntegrationConfigOption{Label: value, Value: value})
	}
	return IntegrationConfigField{Key: key, Label: label, Required: required, Type: "select", Options: options}
}

func paymentDefinition(provider, name, description string, defaults map[string]any, fields ...IntegrationConfigField) IntegrationConfigDefinition {
	common := []IntegrationConfigField{
		integrationField("notify_url", "支付回调地址", false, false, "url"),
		integrationField("return_url", "同步跳转地址", false, false, "url"),
		integrationField("test_amount", "测试金额（最小货币单位）", false, false, "number"),
		integrationField("test_currency", "测试币种", false, false, "text"),
		integrationField("test_extra", "测试下单扩展参数（JSON）", false, false, "textarea"),
		integrationField("test_mode", "允许执行渠道测试", false, false, "switch"),
	}
	if _, exists := defaults["test_amount"]; !exists {
		defaults["test_amount"] = 1
	}
	if _, exists := defaults["test_currency"]; !exists {
		defaults["test_currency"] = "CNY"
	}
	if _, exists := defaults["test_extra"]; !exists {
		defaults["test_extra"] = "{}"
	}
	if _, exists := defaults["test_mode"]; !exists {
		defaults["test_mode"] = false
	}
	fields = append(fields, common...)
	for _, field := range fields {
		if _, exists := defaults[field.Key]; exists {
			continue
		}
		switch field.Type {
		case "number":
			defaults[field.Key] = 0
		case "switch":
			defaults[field.Key] = false
		default:
			defaults[field.Key] = ""
		}
	}
	return IntegrationConfigDefinition{Kind: IntegrationKindPayment, Provider: provider, Name: name, Description: description, Defaults: defaults, Fields: fields}
}

var genericPaymentFields = []IntegrationConfigField{
	integrationField("protocol_version", "协议版本", true, false, "text"),
	integrationField("app_id", "应用 ID", true, false, "text"),
	integrationField("merchant_id", "商户 ID", true, false, "text"),
	integrationField("create_url", "下单接口", true, false, "url"),
	integrationField("query_url", "查单接口", true, false, "url"),
	integrationField("refund_url", "退款接口", true, false, "url"),
	integrationField("app_key", "签名密钥", true, true, "password"),
	integrationField("query_status_field", "查单状态字段", true, false, "text"),
	integrationField("query_success_values", "查单成功值", true, false, "text"),
	integrationField("query_trade_no_field", "商户单号字段", true, false, "text"),
	integrationField("query_provider_trade_no_field", "平台单号字段", true, false, "text"),
	integrationField("query_amount_field", "金额字段", true, false, "text"),
	integrationField("query_currency_field", "币种字段", true, false, "text"),
	integrationField("query_amount_scale", "金额倍率", true, false, "number"),
	integrationField("callback_status_field", "回调状态字段", true, false, "text"),
	integrationField("callback_success_values", "回调成功值", true, false, "text"),
	integrationField("callback_trade_no_field", "回调商户单号字段", true, false, "text"),
	integrationField("callback_provider_trade_no_field", "回调平台单号字段", true, false, "text"),
}

var genericPaymentDefaults = map[string]any{
	"protocol_version": "v1", "app_id": "", "merchant_id": "", "create_url": "", "query_url": "", "refund_url": "", "app_key": "",
	"query_status_field": "", "query_success_values": "", "query_trade_no_field": "",
	"query_provider_trade_no_field": "", "query_amount_field": "", "query_currency_field": "", "query_amount_scale": 1,
	"callback_status_field": "", "callback_success_values": "", "callback_trade_no_field": "",
	"callback_provider_trade_no_field": "", "notify_url": "", "return_url": "",
}

func genericPaymentDefinition(provider, name, description string) IntegrationConfigDefinition {
	defaults := mergeIntegrationDefaults(genericPaymentDefaults, nil)
	fields := append([]IntegrationConfigField(nil), genericPaymentFields...)
	return paymentDefinition(provider, name, description, defaults, fields...)
}

var integrationDefinitions = map[string][]IntegrationConfigDefinition{
	IntegrationKindMQ: {
		{
			Kind: IntegrationKindMQ, Provider: "emqx", Name: "EMQX", Description: "EMQX MQTT 消息服务",
			Defaults: map[string]any{"broker": "tcp://127.0.0.1:1883", "client_id": "kra", "username": "", "password": "", "keep_alive": 30, "clean_session": true, "connect_timeout": 10, "reconnect_interval": 5},
			Fields: []IntegrationConfigField{
				{Key: "broker", Label: "Broker 地址", Type: "text", Required: true, Placeholder: "tcp://127.0.0.1:1883"},
				{Key: "client_id", Label: "客户端 ID", Type: "text", Required: true, Placeholder: "kra"},
				{Key: "username", Label: "用户名", Type: "text"},
				{Key: "password", Label: "密码", Type: "password", Secret: true},
				{Key: "keep_alive", Label: "心跳间隔（秒）", Type: "number", Required: true},
				{Key: "clean_session", Label: "清理会话", Type: "switch", Description: "连接时不恢复 Broker 端保存的旧会话。"},
				{Key: "connect_timeout", Label: "连接超时（秒）", Type: "number", Required: true},
				{Key: "reconnect_interval", Label: "重连退避上限（秒）", Type: "number", Required: true, Description: "网络中断后自动重连的最大退避间隔。"},
			},
		},
		{
			Kind: IntegrationKindMQ, Provider: "rabbitmq", Name: "RabbitMQ", Description: "RabbitMQ AMQP 消息队列",
			Defaults: map[string]any{"host": "127.0.0.1", "port": 5672, "username": "guest", "password": "guest", "vhost": "/", "exchange": "kra", "exchange_type": "topic", "queue": "kra", "routing_key": "#", "durable": true, "auto_delete": false, "prefetch_count": 10, "heartbeat": 10, "connect_timeout": 10, "reconnect_interval": 5, "tls": false},
			Fields: []IntegrationConfigField{
				{Key: "host", Label: "主机", Type: "text", Required: true, Placeholder: "127.0.0.1"},
				{Key: "port", Label: "端口", Type: "number", Required: true},
				{Key: "username", Label: "用户名", Type: "text", Required: true},
				{Key: "password", Label: "密码", Type: "password", Required: true, Secret: true},
				{Key: "vhost", Label: "Virtual Host", Type: "text", Required: true, Placeholder: "/"},
				{Key: "exchange", Label: "Exchange", Type: "text", Required: true, Placeholder: "kra"},
				{Key: "exchange_type", Label: "Exchange 类型", Type: "select", Required: true, Options: []IntegrationConfigOption{{Label: "topic", Value: "topic"}, {Label: "direct", Value: "direct"}, {Label: "fanout", Value: "fanout"}}},
				{Key: "queue", Label: "Queue", Type: "text", Required: true, Placeholder: "kra"},
				{Key: "routing_key", Label: "默认 Routing Key", Type: "text", Required: true, Placeholder: "#", Description: "业务未指定订阅键时使用；topic 类型支持 * 和 #。"},
				{Key: "durable", Label: "持久化", Type: "switch"},
				{Key: "auto_delete", Label: "自动删除", Type: "switch"},
				{Key: "prefetch_count", Label: "预取数量", Type: "number"},
				{Key: "heartbeat", Label: "心跳间隔（秒）", Type: "number"},
				{Key: "connect_timeout", Label: "连接超时（秒）", Type: "number", Required: true},
				{Key: "reconnect_interval", Label: "重连退避上限（秒）", Type: "number", Required: true, Description: "网络中断后自动重连的最大退避间隔。"},
				{Key: "tls", Label: "启用 TLS", Type: "switch"},
			},
		},
	},
	IntegrationKindWebSocket: {
		{
			Kind: IntegrationKindWebSocket, Provider: "melody", Name: "WebSocket", Description: "WebSocket 实时连接服务",
			Defaults: map[string]any{"path": "/ws", "allow_origins": []string{}, "max_message_size": 0, "write_wait": "10s", "pong_wait": "60s", "ping_period": "54s", "message_buffer_size": 0, "concurrent_message_handling": false},
			Fields: []IntegrationConfigField{
				{Key: "path", Label: "访问路径", Type: "text", Required: true, Placeholder: "/ws"},
				{Key: "allow_origins", Label: "允许的来源", Type: "string-list", Placeholder: "https://admin.example.com", Description: "每行一个 Origin；留空时沿用 WebSocket 组件默认策略。"},
				{Key: "max_message_size", Label: "最大消息字节数", Type: "number", Description: "0 表示使用组件默认值。"},
				{Key: "write_wait", Label: "写入超时", Type: "text", Required: true, Placeholder: "10s"},
				{Key: "pong_wait", Label: "Pong 等待时间", Type: "text", Required: true, Placeholder: "60s"},
				{Key: "ping_period", Label: "Ping 间隔", Type: "text", Required: true, Placeholder: "54s"},
				{Key: "message_buffer_size", Label: "消息缓冲区", Type: "number", Description: "0 表示不额外缓冲。"},
				{Key: "concurrent_message_handling", Label: "并发处理消息", Type: "switch"},
			},
		},
	},
	IntegrationKindPayment: {
		paymentDefinition(paymentutil.ProviderAlipay, "支付宝", "支付宝 OpenAPI RSA2 支付", map[string]any{"app_id": "", "private_key": "", "public_key": "", "environment": "production", "sign_type": "RSA2", "gateway_url": "https://openapi.alipay.com/gateway.do", "method": "alipay.trade.create"},
			integrationField("app_id", "应用 ID", true, false, "text"), integrationField("private_key", "应用私钥", true, true, "textarea"), integrationField("public_key", "支付宝公钥", true, true, "textarea"),
			integrationSelect("environment", "环境", false, "production", "sandbox"), integrationSelect("sign_type", "签名算法", false, "RSA2", "RSA"), integrationField("gateway_url", "网关地址", false, false, "url"),
			integrationSelect("method", "默认支付方式", false, "alipay.trade.create", "alipay.trade.pay", "alipay.trade.precreate", "alipay.trade.app.pay", "alipay.trade.page.pay", "alipay.trade.wap.pay")),
		paymentDefinition(paymentutil.ProviderAlipayV3, "支付宝 V3", "支付宝证书模式 V3 接口", map[string]any{"app_id": "", "private_key": "", "app_cert": "", "root_cert": "", "public_cert": "", "environment": "production", "api_base_url": "https://openapi.alipay.com", "gateway_url": "https://openapi.alipay.com/gateway.do", "method": "alipay.trade.create"},
			integrationField("app_id", "应用 ID", true, false, "text"), integrationField("private_key", "应用私钥", false, true, "textarea"), integrationField("app_cert", "应用公钥证书", false, true, "textarea"), integrationField("root_cert", "支付宝根证书", false, true, "textarea"), integrationField("public_cert", "支付宝公钥证书", false, true, "textarea"),
			integrationSelect("environment", "环境", false, "production", "sandbox"), integrationField("api_base_url", "API 地址", false, false, "url"), integrationField("gateway_url", "网关地址", false, false, "url"), integrationSelect("method", "默认支付方式", false, "alipay.trade.create", "alipay.trade.pay", "alipay.trade.precreate", "alipay.trade.app.pay", "alipay.trade.page.pay", "alipay.trade.wap.pay")),
		paymentDefinition(paymentutil.ProviderWechatV2, "微信支付 V2", "微信支付 V2，含退款双向证书", map[string]any{"app_id": "", "merchant_id": "", "mch_key": "", "sign_type": "MD5", "trade_type": "NATIVE", "client_cert": "", "client_key": ""},
			integrationField("app_id", "应用 ID", true, false, "text"), integrationField("merchant_id", "商户号", true, false, "text"), integrationField("mch_key", "API 密钥", true, true, "password"), integrationSelect("sign_type", "签名算法", false, "MD5", "HMAC-SHA256"), integrationSelect("trade_type", "默认交易类型", false, "JSAPI", "APP", "NATIVE", "MWEB", "MICROPAY"), integrationField("client_cert", "商户证书", false, true, "textarea"), integrationField("client_key", "证书私钥", false, true, "textarea")),
		paymentDefinition(paymentutil.ProviderWechatV3, "微信支付 V3", "微信支付 API v3", map[string]any{"app_id": "", "merchant_id": "", "serial_no": "", "private_key": "", "api_v3_key": "", "platform_cert": "", "platform_serial_no": "", "trade_type": "jsapi"},
			integrationField("app_id", "应用 ID", true, false, "text"), integrationField("merchant_id", "商户号", true, false, "text"), integrationField("serial_no", "商户证书序列号", true, false, "text"), integrationField("private_key", "商户私钥", true, true, "textarea"), integrationField("api_v3_key", "API v3 密钥", true, true, "password"), integrationField("platform_cert", "平台证书", true, true, "textarea"), integrationField("platform_serial_no", "平台证书序列号", false, false, "text"), integrationSelect("trade_type", "默认交易类型", false, "jsapi", "app", "native", "h5", "codepay")),
		paymentDefinition(paymentutil.ProviderApple, "Apple IAP", "Apple App Store Server API", map[string]any{"issuer_id": "", "key_id": "", "bundle_id": "", "private_key": "", "price_divisor": 10, "environment": "production", "test_product_id": "", "test_transaction_id": ""},
			integrationField("issuer_id", "Issuer ID", true, false, "text"), integrationField("key_id", "Key ID", true, false, "text"), integrationField("bundle_id", "Bundle ID", true, false, "text"), integrationField("private_key", "P8 私钥", true, true, "textarea"), integrationField("price_divisor", "价格除数", false, false, "number"), integrationSelect("environment", "环境", false, "production", "sandbox"), integrationField("test_product_id", "测试商品 ID", false, false, "text"), integrationField("test_transaction_id", "沙箱交易 ID", false, false, "text")),
		paymentDefinition(paymentutil.ProviderDouyin, "抖音支付", "抖音开放平台支付", map[string]any{"app_id": "", "merchant_id": "", "serial_no": "", "api_key": "", "private_key": "", "platform_cert": "", "platform_serial_no": "", "trade_type": "jsapi", "environment": "production"},
			integrationField("app_id", "应用 ID", true, false, "text"), integrationField("merchant_id", "商户号", true, false, "text"), integrationField("serial_no", "商户证书序列号", true, false, "text"), integrationField("api_key", "API 密钥", true, true, "password"), integrationField("private_key", "商户私钥", true, true, "textarea"), integrationField("platform_cert", "平台证书", true, true, "textarea"), integrationField("platform_serial_no", "平台证书序列号", false, false, "text"), integrationSelect("trade_type", "默认交易类型", false, "app", "jsapi", "h5", "native"), integrationSelect("environment", "环境", false, "production")),
		paymentDefinition(paymentutil.ProviderQQ, "QQ 钱包", "QQ 钱包支付", map[string]any{"mch_id": "", "api_key": "", "sign_type": "MD5", "trade_type": "NATIVE", "cert_file": "", "key_file": "", "environment": "production"},
			integrationField("mch_id", "商户号", true, false, "text"), integrationField("api_key", "API 密钥", true, true, "password"), integrationSelect("sign_type", "签名算法", false, "MD5", "HMAC-SHA256"), integrationSelect("trade_type", "默认交易类型", false, "JSAPI", "NATIVE", "APP", "MICROPAY"), integrationField("cert_file", "退款证书路径", false, false, "text"), integrationField("key_file", "退款私钥路径", false, true, "text"), integrationSelect("environment", "环境", false, "production")),
		paymentDefinition(paymentutil.ProviderAllinPay, "通联支付", "通联收银宝支付", map[string]any{"cus_id": "", "app_id": "", "private_key": "", "public_key": "", "org_id": "", "pay_type": "W02", "query_order_type": "reqsn", "currency": "CNY", "environment": "production"},
			integrationField("cus_id", "商户号", true, false, "text"), integrationField("app_id", "应用 ID", true, false, "text"), integrationField("private_key", "商户私钥", true, true, "textarea"), integrationField("public_key", "平台公钥", true, true, "textarea"), integrationField("org_id", "机构号", false, false, "text"), integrationField("pay_type", "支付类型", false, false, "text"), integrationSelect("query_order_type", "查单标识", false, "reqsn", "trxid"), integrationField("currency", "币种", false, false, "text"), integrationSelect("environment", "环境", false, "production", "sandbox")),
		paymentDefinition(paymentutil.ProviderLakala, "拉卡拉", "拉卡拉聚合支付", map[string]any{"partner_code": "", "credential_code": "", "channel": "Wechat", "method": "jsapi", "currency": "CNY", "environment": "production"},
			integrationField("partner_code", "合作方编号", true, false, "text"), integrationField("credential_code", "凭证码", true, true, "password"), integrationSelect("channel", "支付渠道", false, "Wechat", "Alipay", "UnionPay"), integrationSelect("method", "默认支付方式", false, "jsapi", "h5", "mini", "native", "qrcode", "native_jsapi", "sdk", "web", "retail", "retail_qrcode"), integrationField("currency", "币种", false, false, "text"), integrationSelect("environment", "环境", false, "production")),
		paymentDefinition(paymentutil.ProviderPayPal, "PayPal", "PayPal Checkout", map[string]any{"client_id": "", "client_secret": "", "webhook_id": "", "environment": "sandbox", "return_url": "", "cancel_url": "", "auto_capture": true, "test_currency": "USD"},
			integrationField("client_id", "Client ID", true, false, "text"), integrationField("client_secret", "Client Secret", true, true, "password"), integrationField("webhook_id", "Webhook ID", true, false, "text"), integrationSelect("environment", "环境", false, "sandbox", "production"), integrationField("cancel_url", "取消跳转地址", false, false, "url"), integrationField("auto_capture", "自动捕获", false, false, "switch")),
		paymentDefinition(paymentutil.ProviderSaobei, "扫呗", "扫呗聚合支付", map[string]any{"inst_no": "", "key": "", "merchant_no": "", "terminal_id": "", "access_token": "", "pay_type": "010", "currency": "CNY", "environment": "production"},
			integrationField("inst_no", "机构号", true, false, "text"), integrationField("key", "机构密钥", true, true, "password"), integrationField("merchant_no", "商户号", true, false, "text"), integrationField("terminal_id", "终端号", true, false, "text"), integrationField("access_token", "访问令牌", true, true, "password"), integrationField("pay_type", "支付类型", false, false, "text"), integrationField("currency", "币种", false, false, "text"), integrationSelect("environment", "环境", false, "production", "sandbox")),
		genericPaymentDefinition(paymentutil.ProviderChinaums, "银联商务", "按商户协议配置的银联商务适配器"),
		genericPaymentDefinition(paymentutil.ProviderSFT, "商福通", "按商户协议配置的商福通适配器"),
		genericPaymentDefinition(paymentutil.ProviderSuperPay, "Supper Pay", "按商户协议配置的 Supper Pay 适配器"),
		genericPaymentDefinition(paymentutil.ProviderWechatGame, "微信小游戏支付", "微信小游戏虚拟支付配置驱动适配器"),
		genericPaymentDefinition(paymentutil.ProviderDouyinGame, "抖音小游戏支付", "抖音小游戏支付配置驱动适配器"),
	},
}
