package repository

import (
	"encoding/json"
	"fmt"
	"narasi-ahli-be/app/database"
	"narasi-ahli-be/app/database/entity"
	"narasi-ahli-be/app/database/entity/users"
	"narasi-ahli-be/app/module/users/request"
	"narasi-ahli-be/utils/paginator"
	"strings"

	"github.com/rs/zerolog"
)

type usersRepository struct {
	DB  *database.Database
	Log zerolog.Logger
}

// UsersRepository define interface of IUsersRepository
type UsersRepository interface {
	GetAll(req request.UsersQueryRequest) (userss []*users.Users, paging paginator.Pagination, err error)
	FindOne(id uint) (users *users.Users, err error)
	FindByKeycloakId(keycloakId string) (users *users.Users, err error)
	FindByUsername(username string) (users *users.Users, err error)
	Create(users *users.Users) (userReturn *users.Users, err error)
	Update(id uint, users *users.Users) (err error)
	Delete(id uint) (err error)
	CreateForgotPassword(forgotPasswords *entity.ForgotPasswords) (err error)
	UpdateForgotPassword(id uint, forgotPasswords *entity.ForgotPasswords) (err error)
	FindForgotPassword(keycloakId string, code string) (forgotPasswords *entity.ForgotPasswords, err error)
	CreateOtp(otp *entity.OneTimePasswords) (err error)
	FindOtpByEmail(email string, code string) (otp *entity.OneTimePasswords, err error)
	FindOtpByIdentity(identity string, code string) (otp *entity.OneTimePasswords, err error)
}

func NewUsersRepository(db *database.Database, log zerolog.Logger) UsersRepository {
	return &usersRepository{
		DB:  db,
		Log: log,
	}
}

// implement interface of IUsersRepository
func (_i *usersRepository) GetAll(req request.UsersQueryRequest) (userss []*users.Users, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&users.Users{})

	query = query.Where("is_active = ?", true)

	if req.Username != nil && *req.Username != "" {
		username := strings.ToLower(*req.Username)
		query = query.Where("LOWER(username) LIKE ?", "%"+strings.ToLower(username)+"%")
	}
	if req.Fullname != nil && *req.Fullname != "" {
		fullname := strings.ToLower(*req.Fullname)
		query = query.Where("LOWER(fullname) LIKE ?", "%"+strings.ToLower(fullname)+"%")
	}
	if req.Email != nil && *req.Email != "" {
		query = query.Where("email = ?", req.Email)
	}
	if req.PhoneNumber != nil && *req.PhoneNumber != "" {
		query = query.Where("phone_number = ?", req.PhoneNumber)
	}
	if req.WorkType != nil && *req.WorkType != "" {
		query = query.Where("work_type = ?", req.WorkType)
	}
	if req.GenderType != nil && *req.GenderType != "" {
		query = query.Where("gender_type = ?", req.GenderType)
	}
	if req.IdentityType != nil && *req.IdentityType != "" {
		query = query.Where("identity_type = ?", req.IdentityType)
	}
	if req.IdentityGroup != nil && *req.IdentityGroup != "" {
		query = query.Where("identity_group = ?", req.IdentityGroup)
	}
	if req.IdentityGroupNumber != nil && *req.IdentityGroupNumber != "" {
		query = query.Where("identity_group_number = ?", req.IdentityGroupNumber)
	}
	if req.IdentityNumber != nil && *req.IdentityNumber != "" {
		query = query.Where("identity_number = ?", req.IdentityNumber)
	}
	if req.UserRoleId != nil {
		query = query.Where("user_role_id = ?", req.UserRoleId)
	}
	if req.StatusId != nil {
		query = query.Where("status_id = ?", req.StatusId)
	}
	query.Count(&count)

	if req.Pagination.SortBy != "" {
		direction := "ASC"
		if req.Pagination.Sort == "desc" {
			direction = "DESC"
		}
		query.Order(fmt.Sprintf("%s %s", req.Pagination.SortBy, direction))
	}

	req.Pagination.Count = count
	req.Pagination = paginator.Paging(req.Pagination)

	err = query.Offset(req.Pagination.Offset).Limit(req.Pagination.Limit).Find(&userss).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

func (_i *usersRepository) FindOne(id uint) (users *users.Users, err error) {
	query := _i.DB.DB.Where("id = ?", id)

	if err := query.Preload("UserLevel").First(&users).Error; err != nil {
		return nil, err
	}

	return users, nil
}

func (_i *usersRepository) FindByKeycloakId(keycloakId string) (users *users.Users, err error) {
	query := _i.DB.DB.Where("keycloak_id = ?", keycloakId)
	if err := query.Preload("UserLevel").First(&users).Error; err != nil {
		return nil, err
	}

	return users, nil
}

func (_i *usersRepository) FindByUsername(username string) (users *users.Users, err error) {
	query := _i.DB.DB.Where("username = ?", username)

	if err := query.Preload("UserLevel").First(&users).Error; err != nil {
		return nil, err
	}

	return users, nil
}

func (_i *usersRepository) Create(users *users.Users) (userReturn *users.Users, err error) {
	result := _i.DB.DB.Create(users)
	return users, result.Error
}

func (_i *usersRepository) Update(id uint, userReturn *users.Users) (err error) {
	userReturnMap, err := StructToMap(userReturn)
	delete(userReturnMap, "user_levels")
	_i.Log.Info().Interface("Update", userReturnMap).Msg("")
	if err != nil {
		return err
	}
	query := _i.DB.DB.Model(&users.Users{}).Where(&users.Users{ID: id})
	return query.Updates(userReturnMap).Error
}

func (_i *usersRepository) Delete(id uint) error {
	query := _i.DB.DB.Model(&users.Users{}).Where("id = ?", id)
	return query.Delete(&users.Users{}).Error
}

func (_i *usersRepository) CreateForgotPassword(forgotPasswords *entity.ForgotPasswords) (err error) {
	result := _i.DB.DB.Create(forgotPasswords)
	return result.Error
}

func (_i *usersRepository) UpdateForgotPassword(id uint, forgotPasswords *entity.ForgotPasswords) (err error) {
	_i.Log.Info().Interface("forgotPasswords", id).Msg("")
	_i.Log.Info().Interface("forgotPasswords", forgotPasswords).Msg("")

	return _i.DB.DB.Model(&entity.ForgotPasswords{}).
		Where(&entity.ForgotPasswords{ID: id}).
		Updates(forgotPasswords).Error
}

func (_i *usersRepository) FindForgotPassword(keycloakId string, code string) (forgotPasswords *entity.ForgotPasswords, err error) {
	if err := _i.DB.DB.Where("keycloak_id = ?", keycloakId).Where("code_request = ?", code).Where("is_active = ?", true).First(&forgotPasswords).Error; err != nil {
		return nil, err
	}

	return forgotPasswords, nil
}

func (_i *usersRepository) CreateOtp(otp *entity.OneTimePasswords) (err error) {
	result := _i.DB.DB.Create(otp)
	return result.Error
}

func (_i *usersRepository) FindOtpByEmail(email string, code string) (otp *entity.OneTimePasswords, err error) {
	if err := _i.DB.DB.Where("email = ?", email).Where("otp_code = ?", code).First(&otp).Error; err != nil {
		return nil, err
	}

	return otp, nil
}

func (_i *usersRepository) FindOtpByIdentity(identity string, code string) (otp *entity.OneTimePasswords, err error) {
	if err := _i.DB.DB.Where("identity = ?", identity).Where("otp_code = ?", code).First(&otp).Error; err != nil {
		return nil, err
	}

	return otp, nil
}

func StructToMap(obj interface{}) (map[string]interface{}, error) {
	var result map[string]interface{}
	jsonData, err := json.Marshal(obj)
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal(jsonData, &result)
	if err != nil {
		return nil, err
	}

	return result, nil
}
