package repository

import (
	"fmt"
	"strings"
	"web-qudo-be/app/database"
	"web-qudo-be/app/database/entity"
	"web-qudo-be/app/module/master_modules/request"
	"web-qudo-be/utils/paginator"
)

type masterModulesRepository struct {
	DB *database.Database
}

// MasterModulesRepository define interface of IMasterModulesRepository
type MasterModulesRepository interface {
	GetAll(req request.MasterModulesQueryRequest) (masterModuless []*entity.MasterModules, paging paginator.Pagination, err error)
	FindOne(id uint) (masterModules *entity.MasterModules, err error)
	Create(masterModules *entity.MasterModules) (err error)
	Update(id uint, masterModules *entity.MasterModules) (err error)
	Delete(id uint) (err error)
}

func NewMasterModulesRepository(db *database.Database) MasterModulesRepository {
	return &masterModulesRepository{
		DB: db,
	}
}

// implement interface of IMasterModulesRepository
func (_i *masterModulesRepository) GetAll(req request.MasterModulesQueryRequest) (masterModuless []*entity.MasterModules, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.MasterModules{})
	query = query.Where("is_active = ?", true)

	if req.Name != nil && *req.Name != "" {
		name := strings.ToLower(*req.Name)
		query = query.Where("LOWER(name) LIKE ?", "%"+strings.ToLower(name)+"%")
	}
	if req.Description != nil && *req.Description != "" {
		description := strings.ToLower(*req.Description)
		query = query.Where("LOWER(description) LIKE ?", "%"+strings.ToLower(description)+"%")
	}
	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(&masterModuless).Error
	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

func (_i *masterModulesRepository) FindOne(id uint) (masterModules *entity.MasterModules, err error) {
	if err := _i.DB.DB.First(&masterModules, id).Error; err != nil {
		return nil, err
	}

	return masterModules, nil
}

func (_i *masterModulesRepository) Create(masterModules *entity.MasterModules) (err error) {
	return _i.DB.DB.Create(masterModules).Error
}

func (_i *masterModulesRepository) Update(id uint, masterModules *entity.MasterModules) (err error) {
	return _i.DB.DB.Model(&entity.MasterModules{}).
		Where(&entity.MasterModules{ID: id}).
		Updates(masterModules).Error
}

func (_i *masterModulesRepository) Delete(id uint) error {
	return _i.DB.DB.Delete(&entity.MasterModules{}, id).Error
}
