// 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/errs"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

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

// NewSystemConfigMongo creates a new instance of SystemConfigMgo with the provided MongoDB database.
func NewSystemConfigMongo(db *mongo.Database) (database.SystemConfig, error) {
	coll := db.Collection(database.SystemConfigName)
	_, err := coll.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys:    bson.D{{Key: "key", Value: 1}},
			Options: options.Index().SetUnique(true),
		},
		{
			Keys: bson.D{{Key: "enabled", Value: 1}},
		},
		{
			Keys: bson.D{{Key: "create_time", Value: -1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &SystemConfigMgo{coll: coll}, nil
}

// Create creates a new system config record.
func (s *SystemConfigMgo) Create(ctx context.Context, config *model.SystemConfig) error {
	config.CreateTime = time.Now()
	config.UpdateTime = time.Now()
	return mongoutil.InsertOne(ctx, s.coll, config)
}

// Take retrieves a system config by key. Returns an error if not found.
func (s *SystemConfigMgo) Take(ctx context.Context, key string) (*model.SystemConfig, error) {
	return mongoutil.FindOne[*model.SystemConfig](ctx, s.coll, bson.M{"key": key})
}

// Update updates system config information.
func (s *SystemConfigMgo) Update(ctx context.Context, key string, data map[string]any) error {
	data["update_time"] = time.Now()
	return mongoutil.UpdateOne(ctx, s.coll, bson.M{"key": key}, bson.M{"$set": data}, true)
}

// Find finds system configs by keys.
func (s *SystemConfigMgo) Find(ctx context.Context, keys []string) ([]*model.SystemConfig, error) {
	return mongoutil.Find[*model.SystemConfig](ctx, s.coll, bson.M{"key": bson.M{"$in": keys}})
}

// FindEnabled finds all enabled system configs.
func (s *SystemConfigMgo) FindEnabled(ctx context.Context) ([]*model.SystemConfig, error) {
	return mongoutil.Find[*model.SystemConfig](ctx, s.coll, bson.M{"enabled": true})
}

// FindByKey finds a system config by key (returns nil if not found, no error).
func (s *SystemConfigMgo) FindByKey(ctx context.Context, key string) (*model.SystemConfig, error) {
	config, err := mongoutil.FindOne[*model.SystemConfig](ctx, s.coll, bson.M{"key": key})
	if err != nil {
		if errs.ErrRecordNotFound.Is(err) || err == mongo.ErrNoDocuments {
			return nil, nil
		}
		return nil, err
	}
	return config, nil
}

// Delete deletes a system config by key.
func (s *SystemConfigMgo) Delete(ctx context.Context, key string) error {
	return mongoutil.DeleteOne(ctx, s.coll, bson.M{"key": key})
}
