package repository

import (
	"database/sql"
	"fmt"

	"kfz-goods-pricing/internal/database"
)

// KfzConfig kfz_config 表结构
type KfzConfig struct {
	ID                   int
	NewPrice             float64
	PlaceholderDownPrice float64
	MinShippingFee      float64
	MinPrice             float64
	QueryIndex           int
}

// GetKfzConfig 获取 kfz_config 配置（ID=1）
// 无数据时返回 nil, nil
func GetKfzConfig() (*KfzConfig, error) {
	var cfg KfzConfig
	err := database.DB.QueryRow(
		`SELECT id, new_price, placeholder_down_price, min_shipping_fee, min_price, query_index FROM kfz_config WHERE id=1`,
	).Scan(&cfg.ID, &cfg.NewPrice, &cfg.PlaceholderDownPrice, &cfg.MinShippingFee, &cfg.MinPrice, &cfg.QueryIndex)

	if err == sql.ErrNoRows {
		return nil, nil // 无数据
	}
	if err != nil {
		return nil, fmt.Errorf("查询kfz_config失败: %w", err)
	}
	return &cfg, nil
}

// SaveKfzConfig 保存 kfz_config 配置
// 表中永远只有 ID=1 一条记录：无数据则 INSERT，有数据则 UPDATE
func SaveKfzConfig(cfg *KfzConfig) error {
	var count int
	err := database.DB.QueryRow("SELECT COUNT(*) FROM kfz_config").Scan(&count)
	if err != nil {
		return fmt.Errorf("查询kfz_config失败: %w", err)
	}

	if count == 0 {
		_, err = database.DB.Exec(
			`INSERT INTO kfz_config (id, new_price, placeholder_down_price, min_shipping_fee, min_price, query_index) VALUES (1, ?, ?, ?, ?, ?)`,
			cfg.NewPrice, cfg.PlaceholderDownPrice, cfg.MinShippingFee, cfg.MinPrice, cfg.QueryIndex,
		)
		if err != nil {
			return fmt.Errorf("插入kfz_config失败: %w", err)
		}
	} else {
		_, err = database.DB.Exec(
			`UPDATE kfz_config SET new_price=?, placeholder_down_price=?, min_shipping_fee=?, min_price=?, query_index=? WHERE id=1`,
			cfg.NewPrice, cfg.PlaceholderDownPrice, cfg.MinShippingFee, cfg.MinPrice, cfg.QueryIndex,
		)
		if err != nil {
			return fmt.Errorf("更新kfz_config失败: %w", err)
		}
	}
	return nil
}
