package repository

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

type districtsRepository struct {
	DB *database.Database
}

// DistrictsRepository define interface of IDistrictsRepository
type DistrictsRepository interface {
	GetAll(req request.DistrictsQueryRequest) (districtss []*entity.Districts, paging paginator.Pagination, err error)
	FindOne(id uint) (districts *entity.Districts, err error)
	Create(districts *entity.Districts) (err error)
	Update(id uint, districts *entity.Districts) (err error)
	Delete(id uint) (err error)
}

func NewDistrictsRepository(db *database.Database) DistrictsRepository {
	return &districtsRepository{
		DB: db,
	}
}

// implement interface of IDistrictsRepository
func (_i *districtsRepository) GetAll(req request.DistrictsQueryRequest) (districtss []*entity.Districts, paging paginator.Pagination, err error) {
	var count int64

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

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

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

	paging = *req.Pagination

	return
}

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

	return districts, nil
}

func (_i *districtsRepository) Create(districts *entity.Districts) (err error) {
	return _i.DB.DB.Create(districts).Error
}

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

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