package mongo

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"log"
	"template_blueprint/pkg/models/user"
	"time"
)

func (s *DatabaseService) InsertUser(req user.ReqInsertUser) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	_, err := s.DB.Collection("user").InsertOne(ctx, user.ReqInsertUser{
		ID:       req.ID,
		Name:     req.Name,
		Age:      req.Age,
		Address:  req.Address,
		Gender:   req.Gender,
		Religion: req.Religion,
	})
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

func (s *DatabaseService) GetAllDataUser() ([]*user.User, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	dataUser, err := s.DB.Collection("user").Find(ctx, bson.D{})
	if err != nil {
		log.Println(err)
	}
	var users []*user.User
	err = dataUser.All(ctx, &users)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return users, nil
}

func (s *DatabaseService) GetUserById(id string) (*user.User, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	dataUser := s.DB.Collection("user").FindOne(ctx, bson.D{{Key: "_id", Value: id}})
	var user *user.User
	err := dataUser.Decode(&user)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return user, nil
}

func (s *DatabaseService) UpdateUser(reqUpdate *user.ReqUpdateUser) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	log.Println(reqUpdate.ID)
	filter := bson.M{"_id": reqUpdate.ID}
	update := bson.M{"$set": bson.M{
		"name":     reqUpdate.Name,
		"age":      reqUpdate.Age,
		"address":  reqUpdate.Address,
		"gender":   reqUpdate.Gender,
		"religion": reqUpdate.Religion,
	}}
	updatedData, err := s.DB.Collection("user").UpdateOne(ctx, filter, update)
	if err != nil {
		log.Println(err)
		return err
	}
	log.Println(updatedData)
	return nil
}

func (s *DatabaseService) DeleteUserById(id string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	_, err := s.DB.Collection("user").DeleteOne(ctx, bson.D{{Key: "_id", Value: id}})
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}
