package repository

import (
	"fmt"
	"go-humas-be/app/database"
	"go-humas-be/app/database/entity"
	"go-humas-be/app/module/ppid_data_categories/request"
	"go-humas-be/utils/paginator"
	"strings"
)

type ppidDataCategoriesRepository struct {
	DB *database.Database
}

// PpidDataCategoriesRepository define interface of IPpidDataCategoriesRepository
type PpidDataCategoriesRepository interface {
	GetAll(req request.PpidDataCategoriesQueryRequest) (ppidDataCategoriess []*entity.PpidDataCategories, paging paginator.Pagination, err error)
	FindOne(id uint) (ppidDataCategories *entity.PpidDataCategories, err error)
	Create(ppidDataCategories *entity.PpidDataCategories) (err error)
	Update(id uint, ppidDataCategories *entity.PpidDataCategories) (err error)
	Delete(id uint) (err error)
}

func NewPpidDataCategoriesRepository(db *database.Database) PpidDataCategoriesRepository {
	return &ppidDataCategoriesRepository{
		DB: db,
	}
}

// implement interface of IPpidDataCategoriesRepository
func (_i *ppidDataCategoriesRepository) GetAll(req request.PpidDataCategoriesQueryRequest) (ppidDataCategoriess []*entity.PpidDataCategories, paging paginator.Pagination, err error) {
	var count int64

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

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

	paging = *req.Pagination

	return
}

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

	return ppidDataCategories, nil
}

func (_i *ppidDataCategoriesRepository) Create(ppidDataCategories *entity.PpidDataCategories) (err error) {
	return _i.DB.DB.Create(ppidDataCategories).Error
}

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

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