package repository

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

type masterStatusesRepository struct {
	DB *database.Database
}

// MasterStatusesRepository define interface of IMasterStatusesRepository
type MasterStatusesRepository interface {
	GetAll(req request.MasterStatusesQueryRequest) (masterStatusess []*entity.MasterStatuses, paging paginator.Pagination, err error)
	FindOne(id uint) (masterStatuses *entity.MasterStatuses, err error)
	Create(masterStatuses *entity.MasterStatuses) (err error)
	Update(id uint, masterStatuses *entity.MasterStatuses) (err error)
	Delete(id uint) (err error)
}

func NewMasterStatusesRepository(db *database.Database) MasterStatusesRepository {
	return &masterStatusesRepository{
		DB: db,
	}
}

// implement interface of IMasterStatusesRepository
func (_i *masterStatusesRepository) GetAll(req request.MasterStatusesQueryRequest) (masterStatusess []*entity.MasterStatuses, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.MasterStatuses{})
	query.Count(&count)

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

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

	paging = *req.Pagination

	return
}

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

	return masterStatuses, nil
}

func (_i *masterStatusesRepository) Create(masterStatuses *entity.MasterStatuses) (err error) {
	return _i.DB.DB.Create(masterStatuses).Error
}

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

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