package repository

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

type citiesRepository struct {
	DB *database.Database
}

// CitiesRepository define interface of ICitiesRepository
type CitiesRepository interface {
	GetAll(req request.CitiesQueryRequest) (citiess []*entity.Cities, paging paginator.Pagination, err error)
	FindOne(id uint) (cities *entity.Cities, err error)
	Create(cities *entity.Cities) (err error)
	Update(id uint, cities *entity.Cities) (err error)
	Delete(id uint) (err error)
}

func NewCitiesRepository(db *database.Database) CitiesRepository {
	return &citiesRepository{
		DB: db,
	}
}

// implement interface of ICitiesRepository
func (_i *citiesRepository) GetAll(req request.CitiesQueryRequest) (citiess []*entity.Cities, paging paginator.Pagination, err error) {
	var count int64

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

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

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

	paging = *req.Pagination

	return
}

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

	return cities, nil
}

func (_i *citiesRepository) Create(cities *entity.Cities) (err error) {
	return _i.DB.DB.Create(cities).Error
}

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

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