// Copyright © 2023 OpenIM. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package mgo

import (
	"context"
	"time"

	"git.imall.cloud/openim/open-im-server-deploy/pkg/common/storage/database"
	"git.imall.cloud/openim/open-im-server-deploy/pkg/common/storage/model"
	"github.com/openimsdk/tools/db/mongoutil"
	"github.com/openimsdk/tools/db/pagination"
	"github.com/openimsdk/tools/errs"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// MeetingCheckInMgo implements MeetingCheckIn using MongoDB as the storage backend.
type MeetingCheckInMgo struct {
	coll *mongo.Collection
}

// NewMeetingCheckInMongo creates a new instance of MeetingCheckInMgo with the provided MongoDB database.
func NewMeetingCheckInMongo(db *mongo.Database) (database.MeetingCheckIn, error) {
	coll := db.Collection(database.MeetingCheckInName)
	_, err := coll.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys:    bson.D{{Key: "check_in_id", Value: 1}},
			Options: options.Index().SetUnique(true),
		},
		{
			Keys: bson.D{{Key: "meeting_id", Value: 1}, {Key: "user_id", Value: 1}},
			Options: options.Index().SetUnique(true), // 一个用户在一个会议中只能签到一次
		},
		{
			Keys: bson.D{{Key: "meeting_id", Value: 1}, {Key: "check_in_time", Value: -1}},
		},
		{
			Keys: bson.D{{Key: "user_id", Value: 1}, {Key: "check_in_time", Value: -1}},
		},
	})
	if err != nil {
		return nil, errs.Wrap(err)
	}
	return &MeetingCheckInMgo{coll: coll}, nil
}

// Create creates a new meeting check-in record.
func (m *MeetingCheckInMgo) Create(ctx context.Context, checkIn *model.MeetingCheckIn) error {
	if checkIn.CreateTime.IsZero() {
		checkIn.CreateTime = time.Now()
	}
	if checkIn.CheckInTime.IsZero() {
		checkIn.CheckInTime = time.Now()
	}
	return mongoutil.InsertOne(ctx, m.coll, checkIn)
}

// Take retrieves a check-in by check-in ID. Returns an error if not found.
func (m *MeetingCheckInMgo) Take(ctx context.Context, checkInID string) (*model.MeetingCheckIn, error) {
	return mongoutil.FindOne[*model.MeetingCheckIn](ctx, m.coll, bson.M{"check_in_id": checkInID})
}

// FindByMeetingID finds all check-ins for a meeting with pagination.
func (m *MeetingCheckInMgo) FindByMeetingID(ctx context.Context, meetingID string, pagination pagination.Pagination) (total int64, checkIns []*model.MeetingCheckIn, err error) {
	filter := bson.M{"meeting_id": meetingID}
	return mongoutil.FindPage[*model.MeetingCheckIn](ctx, m.coll, filter, pagination, &options.FindOptions{
		Sort: bson.D{{Key: "check_in_time", Value: -1}},
	})
}

// FindByUserAndMeetingID finds if a user has checked in for a specific meeting.
func (m *MeetingCheckInMgo) FindByUserAndMeetingID(ctx context.Context, userID, meetingID string) (*model.MeetingCheckIn, error) {
	return mongoutil.FindOne[*model.MeetingCheckIn](ctx, m.coll, bson.M{
		"user_id":   userID,
		"meeting_id": meetingID,
	})
}

// CountByMeetingID counts the number of check-ins for a meeting.
func (m *MeetingCheckInMgo) CountByMeetingID(ctx context.Context, meetingID string) (int64, error) {
	return mongoutil.Count(ctx, m.coll, bson.M{"meeting_id": meetingID})
}

// FindByUser finds all check-ins by a user with pagination.
func (m *MeetingCheckInMgo) FindByUser(ctx context.Context, userID string, pagination pagination.Pagination) (total int64, checkIns []*model.MeetingCheckIn, err error) {
	filter := bson.M{"user_id": userID}
	return mongoutil.FindPage[*model.MeetingCheckIn](ctx, m.coll, filter, pagination, &options.FindOptions{
		Sort: bson.D{{Key: "check_in_time", Value: -1}},
	})
}

// Delete deletes a check-in by check-in ID.
func (m *MeetingCheckInMgo) Delete(ctx context.Context, checkInID string) error {
	return mongoutil.DeleteOne(ctx, m.coll, bson.M{"check_in_id": checkInID})
}

