// Code generated by goctl. DO NOT EDIT.
// goctl 1.8.1

package model

import (
	"context"
	"time"

	"github.com/zeromicro/go-zero/core/stores/mon"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
)

type appsModel interface {
	Insert(ctx context.Context, data *Apps) error
	FindOne(ctx context.Context, id string) (*Apps, error)
	Update(ctx context.Context, data *Apps) (*mongo.UpdateResult, error)
	UpdateInfo(ctx context.Context, data *Apps) (*mongo.UpdateResult, error)
	Delete(ctx context.Context, id string) (int64, error)
	FindAll(ctx context.Context, teamId primitive. ObjectID, apptype string, keyword *string) ([]*Apps, error)
}

type defaultAppsModel struct {
	conn *mon.Model
}

func newDefaultAppsModel(conn *mon.Model) *defaultAppsModel {
	return &defaultAppsModel{conn: conn}
}

func (m *defaultAppsModel) Insert(ctx context.Context, data *Apps) error {
	if data.ID.IsZero() {
		data.ID = primitive.NewObjectID()
		data.UpdateTime = time.Now()
	}

	_, err := m.conn.InsertOne(ctx, data)
	return err
}

func (m *defaultAppsModel) FindOne(ctx context.Context, id string) (*Apps, error) {
	oid, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return nil, ErrInvalidObjectId
	}

	var data Apps

	err = m.conn.FindOne(ctx, &data, bson.M{"_id": oid})
	switch err {
	case nil:
		return &data, nil
	case mon.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultAppsModel) Update(ctx context.Context, data *Apps) (*mongo.UpdateResult, error) {
	data.UpdateTime = time.Now()

	res, err := m.conn.UpdateOne(ctx, bson.M{"_id": data.ID}, bson.M{"$set": data})
	return res, err
}

func (m *defaultAppsModel) UpdateInfo(ctx context.Context, data *Apps) (*mongo.UpdateResult, error) {
	data.UpdateTime = time.Now()

	res, err := m.conn.UpdateOne(ctx, bson.M{"_id": data.ID}, bson.M{
		"$set": bson.M{
			"name":  data.Name,
			"intro": data.Intro,
		},
	})
	return res, err
}

func (m *defaultAppsModel) Delete(ctx context.Context, id string) (int64, error) {
	oid, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return 0, ErrInvalidObjectId
	}

	res, err := m.conn.DeleteOne(ctx, bson.M{"_id": oid})
	return res, err
}

func (m *defaultAppsModel) FindAll(ctx context.Context, teamId primitive. ObjectID, apptype string, keyword *string) ([]*Apps, error) {
	var data []*Apps

	k := ""
	if keyword != nil {
		k = *keyword
	}

	err := m.conn.Find(ctx, &data, bson.M{
		"teamId": teamId,
		"type": apptype,
		"name": bson.M{
			"$regex":   k, // 用你想要匹配的模式替换 searchPattern
			"$options": "i",              // 可选：i 表示不区分大小写
		},
	})
	switch err {
	case nil:
		return data, nil
	case mon.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}