package main

import (
	"context"
	"gopkg.in/mgo.v2/bson"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// ChatRecord 表示聊天记录的结构
/*type ChatRecord struct {
	//Id         bson.ObjectId `bson:"_id,omitempty"`
	SenderId   int64 `bson:"senderId"`
	ReceiverId int64 `bson:"receiverId"`
	//Timestamp  time.Time `bson:"timestamp"`
	StartTime int64  `bson:"startTime"` // 创建时间
	EndTime   int64  `bson:"endTime"`   // 单条消息结束时间
	Message   string `bson:"message"`
}
*/
type ChatRecord struct {
	ID       bson.ObjectId `bson:"_id,omitempty"`
	CreateAt int64         `json:"create_at"`
	Content  map[string]*Message
}

type Message struct {
	SenderId  int64  `bson:"senderId"`
	StartTime int64  `bson:"startTime"` // 创建时间
	EndTime   int64  `bson:"endTime"`   // 过期时间
	Content   string `bson:"content"`   // 内容

}

var MongoDBClient *mongo.Client

// 连接到 MongoDB
func setupMongoDB() *mongo.Client {
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
	if err != nil {
		log.Fatal(err)
	}

	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	err = client.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}

	return client
}

func saveChatRecord(record ChatRecord) error {
	client := setupMongoDB()
	defer client.Disconnect(context.Background())

	collection := client.Database("chat_db").Collection("chat_records")

	_, err := collection.InsertOne(context.Background(), record)
	if err != nil {
		return err
	}

	return nil
}
