package history

import (
	"database/sql"
	"encoding/json"
	"fmt"
	mysqlmgr "server/db/mysql"
	"server/msg"
	"strings"
	"time"
)

func AddHistory(room_info *msg.RoomInfo) (int64, error) {
	jsonData, err := json.Marshal(room_info)
	if err != nil {
		return 0, fmt.Errorf("failed to marshal room info: %v", err)
	}
	now := time.Now()
	room_id, err := mysqlmgr.Insert("INSERT INTO ludo_roominfo (create_time,room_info) VALUES (?,?)", now, jsonData)
	if err != nil {
		return 0, fmt.Errorf("failed to insert room info: %v", err)
	}
	var userIDs []string = make([]string, 0, 4)

	for _, v := range room_info.Colors {
		if !strings.Contains(v.MId, "robot") {
			userIDs = append(userIDs, v.MId)
		}
	}

	err = addUsersHistoryToRoom(room_id, userIDs)
	if err != nil {
		return 0, fmt.Errorf("addUsersToRoom failed to insert room info: %v", err)
	}

	return room_id, nil
}

func addUsersHistoryToRoom(roomID int64, userIDs []string) error {
	if len(userIDs) == 0 {
		return nil
	}

	query := "INSERT INTO ludo_history (create_time, room_id, user_id) VALUES "
	var args []interface{}
	now := time.Now() // Same timestamp for all entries

	for i, userID := range userIDs {
		if i > 0 {
			query += ", "
		}
		query += "(?, ?, ?)"
		args = append(args, now, roomID, userID)
	}

	_, err := mysqlmgr.Insert(query, args...)
	return err
}

type HistoryRecord struct {
	ID         int       `db:"id"`
	CreateTime time.Time `db:"create_time"`
	RoomID     int       `db:"room_id"`
	UserID     string    `db:"user_id"`
}

func GetHistoryByUserID(userID string) ([]*msg.HistoryRecord, error) {
	rows, err := mysqlmgr.Query("SELECT id, create_time, room_id, user_id FROM ludo_history WHERE user_id = ?", userID)
	if err != nil {
		return nil, fmt.Errorf("query failed: %v", err)
	}
	defer rows.Close()

	var results []*msg.HistoryRecord

	for rows.Next() {
		var record HistoryRecord
		if err := rows.Scan(&record.ID, &record.CreateTime, &record.RoomID, &record.UserID); err != nil {
			return nil, fmt.Errorf("failed to scan row: %v", err)
		}
		results = append(results, &msg.HistoryRecord{
			Id:     int32(record.ID),
			RoomId: int32(record.RoomID),
			UserId: record.UserID,
			Time:   record.CreateTime.Local().String(),
		})
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("rows error: %v", err)
	}

	return results, nil
}

func GetRoomInfoByID(id int) (*msg.RoomInfo, error) {
	// Query the database
	row := mysqlmgr.QueryRow("SELECT room_info FROM ludo_roominfo WHERE id = ?", id)

	// This will hold the raw JSON data from the database
	var jsonData []byte

	// Scan the result into jsonData
	if err := row.Scan(&jsonData); err != nil {
		if err == sql.ErrNoRows {
			return nil, fmt.Errorf("room info not found for id %d", id)
		}
		return nil, fmt.Errorf("failed to scan room info: %v", err)
	}

	// Unmarshal the JSON into RoomInfo struct
	var roomInfo msg.RoomInfo
	if err := json.Unmarshal(jsonData, &roomInfo); err != nil {
		return nil, fmt.Errorf("failed to unmarshal room info: %v", err)
	}

	return &roomInfo, nil
}
