package mongos

import (
	"context"
	"errors"
	"github.com/Pena-Co-Ltd/amocrm_templategen_back/dal/model"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.uber.org/zap"
	"time"
)

type GDisk struct {
	coll   *mongo.Collection
	logger *zap.Logger
}

func InitGDisk(db *mongo.Database, logger *zap.Logger) *GDisk {
	return &GDisk{coll: db.Collection("gDisk"), logger: logger}
}

func (d *GDisk) InsertOrUpdate(ctx context.Context, record *model.GDisk) (string, error) {
	record.CreatedAt = time.Now()
	record.UpdatedAt = record.CreatedAt

	var found *model.GDisk
	var err error

	if record.ID != "" {
		found, err = d.GetByID(ctx, record.ID)
	} else if record.Email != "" {
		found, err = d.GetByEmail(ctx, record.Email)
	} else {
		err = errors.New("got empty id and email")
	}

	if err != nil {
		d.logger.Error("ErrorInsertOrUpdateGDisk", zap.Error(err))
		return "", err
	}

	if found == nil {
		// Set default TemplateFolder && SaveFolder
		if record.TemplateFolder == "" {
			record.TemplateFolder = "templategen/templates"
		}
		if record.SaveFolder == "" {
			record.SaveFolder = "templategen/saved"
		}

		result, err := d.coll.InsertOne(ctx, record)
		if err != nil {
			d.logger.Error("ErrorInsertOrUpdateGDisk", zap.Error(err))
			return "", err
		}

		return result.InsertedID.(primitive.ObjectID).Hex(), nil
	}

	record.CreatedAt = found.CreatedAt

	err = d.Update(ctx, record)
	if err != nil {
		d.logger.Error("ErrorInsertOrUpdateGDisk", zap.Error(err))
		return "", err
	}

	return found.ID, nil
}

func (d *GDisk) GetByID(ctx context.Context, id string) (*model.GDisk, error) {
	objID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		d.logger.Error("ErrorGetGDisk", zap.Error(err))
		return nil, err
	}

	filter := bson.M{"_id": objID, "is_deleted": false}

	var result model.GDisk

	err = d.coll.FindOne(ctx, filter).Decode(&result)

	if err == mongo.ErrNoDocuments {
		return nil, nil
	} else {
		if err != nil {
			d.logger.Error("ErrorGetGDisk", zap.Error(err))
			return nil, err
		}
	}

	d.logger.Info("InfoGetGDisk", zap.String("id", result.ID))
	return &result, nil
}

func (d *GDisk) GetByEmail(ctx context.Context, email string) (*model.GDisk, error) {
	filter := bson.M{"email": email, "is_deleted": false}

	var result model.GDisk

	err := d.coll.FindOne(ctx, filter).Decode(&result)

	if err == mongo.ErrNoDocuments {
		return nil, nil
	} else {
		if err != nil {
			d.logger.Error("ErrorGetGDisk", zap.Error(err))
			return nil, err
		}
	}

	d.logger.Info("InfoGetGDisk", zap.String("id", result.ID))
	return &result, nil
}

func (d *GDisk) GetListByUserID(ctx context.Context, userID string) ([]model.GDisk, error) {
	filter := bson.M{"user_id": userID, "is_deleted": false}

	var result []model.GDisk

	cur, err := d.coll.Find(ctx, filter)

	if err == mongo.ErrNoDocuments {
		return nil, nil
	} else {
		if err != nil {
			d.logger.Error("ErrorGetListGDisk", zap.Error(err))
			return nil, err
		}
	}

	err = cur.All(ctx, &result)
	if err != nil {
		d.logger.Error("ErrorGetListGDisk", zap.Error(err))
		return nil, err
	}

	d.logger.Info("InfoGetListGDisk")
	return result, nil
}

func (d *GDisk) Update(ctx context.Context, record *model.GDisk) error {
	filter := bson.M{"is_deleted": false}

	if record.ID != "" {
		objID, err := primitive.ObjectIDFromHex(record.ID)

		if err != nil {
			d.logger.Error("ErrorUpdateGDisk", zap.Error(err))
			return err
		}
		filter["_id"] = objID
	} else if record.Email != "" {
		filter["email"] = record.Email
	} else {
		err := errors.New("got empty id and email")
		d.logger.Error("ErrorUpdateGDisk", zap.Error(err))
		return err
	}

	update := bson.M{"updated_at": time.Now()}

	if record.DisplayName != "" {
		update["display_name"] = record.DisplayName
	}

	if record.Email != "" {
		update["email"] = record.Email
	}

	if record.PhotoLink != "" {
		update["photo_link"] = record.PhotoLink
	}

	if record.AccessToken != "" {
		update["access_token"] = record.AccessToken
	}

	if record.RefreshToken != "" {
		update["refresh_token"] = record.RefreshToken
	}

	if !record.ExpiresIn.IsZero() {
		update["expires_in"] = record.ExpiresIn
	}

	if record.TokenType != "" {
		update["token_type"] = record.TokenType
	}

	if record.TemplateFolder != "" {
		update["template_folder"] = record.TemplateFolder
	}

	if record.TemplateFolderID != "" {
		update["template_folder_id"] = record.TemplateFolderID
	}

	if record.SaveFolder != "" {
		update["save_folder"] = record.SaveFolder
	}

	if record.SaveFolderID != "" {
		update["save_folder_id"] = record.SaveFolderID
	}

	_, err := d.coll.UpdateOne(ctx, filter, bson.D{{"$set", update}})

	if err != nil {
		d.logger.Error("ErrorUpdateGDisk", zap.Error(err))
		return err
	}

	return nil
}

func (d *GDisk) DeleteByUserID(ctx context.Context, userID string) error {
	if userID == "" {
		err := errors.New("got empty user id")
		d.logger.Error("ErrorDeleteGDisk", zap.Error(err))
		return err
	}

	filter := bson.M{"user_id": userID, "is_deleted": false}

	update := bson.M{"updated_at": time.Now(), "is_deleted": true}

	_, err := d.coll.UpdateOne(ctx, filter, bson.D{{"$set", update}})
	if err != nil {
		d.logger.Error("ErrorDeleteGDisk", zap.Error(err))
		return err
	}

	return nil
}
