package repository

import (
	"database/sql"
	"fmt"

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

// GoodsPricing 商品定价记录
type GoodsPricing struct {
	ID                   int64
	ISBN                 string
	BookName             string
	Author               string
	Publishing           string
	OutID                string
	Quality              string
	QueryIndex           int
	UserID               string
	Price                float64
	ShippingFee          float64
	FailCount            int
	PlaceholderDownPrice float64
	MinShippingFee       float64
	MinPrice             float64
}

// GoodsRepository 商品仓储
type GoodsRepository struct{}

// NewGoodsRepository 创建商品仓储实例
func NewGoodsRepository() *GoodsRepository {
	return &GoodsRepository{}
}

// Insert 插入查询记录，返回自增ID
func (r *GoodsRepository) Insert(isbn, bookName, author, publishing, outID, quality, userID string, queryIndex int, placeholderDownPrice, minShippingFee, minPrice float64) (int64, error) {
	query := `INSERT INTO goods_pricing (isbn, book_name, author, publishing, out_id, quality, query_index, user_id, fail_count, placeholder_down_price, min_shipping_fee, min_price) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)`

	result, err := database.DB.Exec(query, isbn, bookName, author, publishing, outID, quality, queryIndex, userID, placeholderDownPrice, minShippingFee, minPrice)
	if err != nil {
		return 0, fmt.Errorf("插入记录失败: %w", err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		return 0, fmt.Errorf("获取自增ID失败: %w", err)
	}

	return id, nil
}

// UpdatePrice 更新价格和运费
func (r *GoodsRepository) UpdatePrice(id int64, price, shippingFee, finalPrice float64) error {
	query := `UPDATE goods_pricing SET price = ?, shipping_fee = ?,final_price = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`

	_, err := database.DB.Exec(query, price, shippingFee, finalPrice, id)
	if err != nil {
		return fmt.Errorf("更新价格失败: %w", err)
	}

	return nil
}

// MarkFailed 标记查询失败，fail_count+1，更新updated_at
func (r *GoodsRepository) MarkFailed(id int64) {
	query := `UPDATE goods_pricing SET fail_count = fail_count + 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?`
	database.DB.Exec(query, id)
}

// GetByID 根据ID查询记录
func (r *GoodsRepository) GetByID(id int64) (*GoodsPricing, error) {
	query := `SELECT id, isbn, out_id, quality, query_index, user_id, price, shipping_fee FROM goods_pricing WHERE id = ?`

	row := database.DB.QueryRow(query, id)

	var record GoodsPricing
	var price, shippingFee sql.NullFloat64

	err := row.Scan(&record.ID, &record.ISBN, &record.OutID, &record.Quality, &record.QueryIndex, &record.UserID, &price, &shippingFee)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, fmt.Errorf("记录不存在")
		}
		return nil, fmt.Errorf("查询记录失败: %w", err)
	}

	if price.Valid {
		record.Price = price.Float64
	}
	if shippingFee.Valid {
		record.ShippingFee = shippingFee.Float64
	}

	return &record, nil
}

// GetByISBN 根据ISBN查询记录列表
func (r *GoodsRepository) GetByISBN(isbn string) ([]*GoodsPricing, error) {
	query := `SELECT id, isbn, out_id, quality, query_index, user_id, price, shipping_fee FROM goods_pricing WHERE isbn = ? ORDER BY created_at DESC`

	rows, err := database.DB.Query(query, isbn)
	if err != nil {
		return nil, fmt.Errorf("查询记录失败: %w", err)
	}
	defer rows.Close()

	var records []*GoodsPricing
	for rows.Next() {
		var record GoodsPricing
		var price, shippingFee sql.NullFloat64

		err := rows.Scan(&record.ID, &record.ISBN, &record.OutID, &record.Quality, &record.QueryIndex, &record.UserID, &price, &shippingFee)
		if err != nil {
			return nil, fmt.Errorf("扫描记录失败: %w", err)
		}

		if price.Valid {
			record.Price = price.Float64
		}
		if shippingFee.Valid {
			record.ShippingFee = shippingFee.Float64
		}

		records = append(records, &record)
	}

	return records, nil
}

// GetAllOrderByUpdatedAt 查询一条price为空的记录，按fail_count升序、updated_at倒序
func (r *GoodsRepository) GetAllOrderByUpdatedAt() (*GoodsPricing, error) {
	query := `SELECT id, isbn, book_name, author, publishing, out_id, quality, query_index, user_id, price, shipping_fee, fail_count, placeholder_down_price, min_shipping_fee, min_price FROM goods_pricing WHERE final_price IS NULL OR final_price = 0 ORDER BY fail_count ASC, updated_at DESC LIMIT 1`

	row := database.DB.QueryRow(query)

	var record GoodsPricing
	var price, shippingFee sql.NullFloat64
	var placeholderDownPrice, minShippingFee, minPrice sql.NullFloat64

	err := row.Scan(&record.ID, &record.ISBN, &record.BookName, &record.Author, &record.Publishing, &record.OutID, &record.Quality, &record.QueryIndex, &record.UserID, &price, &shippingFee, &record.FailCount, &record.PlaceholderDownPrice, &record.MinShippingFee, &record.MinPrice)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, nil
		}
		return nil, fmt.Errorf("查询记录失败: %w", err)
	}

	if price.Valid {
		record.Price = price.Float64
	}
	if shippingFee.Valid {
		record.ShippingFee = shippingFee.Float64
	}

	if placeholderDownPrice.Valid {
		record.PlaceholderDownPrice = placeholderDownPrice.Float64
	}

	if minShippingFee.Valid {
		record.MinShippingFee = minShippingFee.Float64
	}

	if minPrice.Valid {
		record.MinPrice = minPrice.Float64
	}

	return &record, nil
}
