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 YaDisk struct {
	coll   *mongo.Collection
	logger *zap.Logger
}

func InitYaDisk(db *mongo.Database, logger *zap.Logger) *YaDisk {
	return &YaDisk{coll: db.Collection("yaDisk"), logger: logger}
}

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

	var found *model.YaDisk
	var err error

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

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

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

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

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

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

	return found.ID, nil
}

func (d *YaDisk) GetByID(ctx context.Context, id string) (*model.YaDisk, 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.YaDisk

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

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

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

func (d *YaDisk) GetByLogin(ctx context.Context, login string) (*model.YaDisk, error) {
	filter := bson.M{"login": login, "is_deleted": false}

	var result model.YaDisk

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

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

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

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

	var result []model.YaDisk

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

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

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

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

// Update - обновляет запись по её id или логину Yandex
func (d *YaDisk) Update(ctx context.Context, record *model.YaDisk) error {
	filter := bson.M{"is_deleted": false}

	if record.ID != "" {
		objID, err := primitive.ObjectIDFromHex(record.ID)
		if err != nil {
			d.logger.Error("ErrorUpdateYaDisk", zap.Error(err))
			return err
		}

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

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

	if record.UID != "" {
		update["uid"] = record.UID
	}

	if record.Login != "" {
		update["login"] = record.Login
	}

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

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

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

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

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

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

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

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

	return nil
}

func (d *YaDisk) DeleteByUserID(ctx context.Context, userID string) error {
	if userID == "" {
		err := errors.New("got empty user id")
		d.logger.Error("ErrorDeleteYaDisk", 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.UpdateMany(ctx, filter, bson.D{{"$set", update}})
	if err != nil {
		d.logger.Error("ErrorDeleteYaDisk", zap.Error(err))
		return err
	}

	return nil
}
