package model

import (
	"crawler/config"
	"crawler/service"
	"database/sql"
	"log"
)

type OrderDetailModel struct {
	OrderDetail
}

type OrderDetail struct {
	ID              int    `json:"id"`
	OrderID         int    `json:"order_id"`
	ProductID       int    `json:"product_id"`
	ProductOptionID int    `json:"product_option_id"`
	GamePos         int    `json:"game_pos"`
	GameID          int    `json:"game_id"`
	OrderProductID  string `json:"OrderProductID"`
}

func (this *OrderDetailModel) IsExists(orderID, orderDetailID int) bool {
	var (
		db     = service.DB_PLAYR
		conn   = db.SQLDB
		query  = "SELECT IF(COUNT(*) <= 0, 0, 1) AS `exists` FROM tb_order_detail WHERE id = ? AND order_id = ?;"
		exists = false
	)

	stmt, err := conn.Prepare(query)
	if err != nil {
		log.Fatal(err)
	}

	err = stmt.QueryRow(orderDetailID, orderID).Scan(&exists)
	if err != nil {
		db.SetErrorLog(err, query)
		return exists
	}

	db.SetGeneralLog(config.GL_ACTION_SELECT, query, "select exists order detail")
	return exists
}

func (this *OrderDetailModel) Info(orderID, orderDetailID int) (OrderDetail, error) {
	var (
		db    = service.DB_PLAYR
		conn  = db.SQLDB
		query = `SELECT id, order_id, product_id, product_option_id, game_pos, game_id,
					(CASE WHEN game_pos = 1 THEN
					  (SELECT CWS.code FROM tb_cws_product CWS WHERE CWS.id = game_id LIMIT 1)
					WHEN game_pos = 2 THEN
					  (SELECT G2A.id FROM tb_g2a_product G2A WHERE G2A.index = game_id LIMIT 1)
					ELSE
					  NULL
					END) AS OrderProductID
					FROM tb_order_detail WHERE id = ? AND order_id = ?;`
		info OrderDetail
	)

	err := conn.QueryRow(query, orderDetailID, orderID).Scan(
		&info.ID, &info.OrderID, &info.ProductID, &info.ProductOptionID, &info.GamePos, &info.GameID, &info.OrderProductID,
	)

	if err != nil && err != sql.ErrNoRows {
		db.SetErrorLog(err, query)
		return info, err
	}

	db.SetGeneralLog(config.GL_ACTION_SELECT, query, "select order detail info")
	return info, nil
}
