package repository

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

type provincesRepository struct {
	DB *database.Database
}

// ProvincesRepository define interface of IProvincesRepository
type ProvincesRepository interface {
	GetAll(req request.ProvincesQueryRequest) (provincess []*entity.Provinces, paging paginator.Pagination, err error)
	FindOne(id uint) (provinces *entity.Provinces, err error)
	Create(provinces *entity.Provinces) (err error)
	Update(id uint, provinces *entity.Provinces) (err error)
	Delete(id uint) (err error)
}

func NewProvincesRepository(db *database.Database) ProvincesRepository {
	return &provincesRepository{
		DB: db,
	}
}

// implement interface of IProvincesRepository
func (_i *provincesRepository) GetAll(req request.ProvincesQueryRequest) (provincess []*entity.Provinces, paging paginator.Pagination, err error) {
	var count int64

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

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

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

	paging = *req.Pagination

	return
}

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

	return provinces, nil
}

func (_i *provincesRepository) Create(provinces *entity.Provinces) (err error) {
	return _i.DB.DB.Create(provinces).Error
}

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

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