package repository

import (
	"go-humas-be/app/database"
	"go-humas-be/app/database/entity"
)

type ppidDataApprovalHistoriesRepository struct {
	DB *database.Database
}

// PpidDataApprovalHistoriesRepository define interface of IPpidDataApprovalHistoriesRepository
type PpidDataApprovalHistoriesRepository interface {
	GetAll() (ppidDataApprovalHistories []*entity.PpidDataApprovalHistories, err error)
	FindOne(id uint) (ppidDataApprovalHistories *entity.PpidDataApprovalHistories, err error)
	FindByPpidData(ppidDataId uint) (ppidDataApprovalHistories []*entity.PpidDataApprovalHistories, err error)
	Create(ppidDataApprovalHistories *entity.PpidDataApprovalHistories) (err error)
	Update(id uint, ppidDataApprovalHistories *entity.PpidDataApprovalHistories) (err error)
	Delete(id uint) (err error)
}

func NewPpidDataApprovalHistoriesRepository(db *database.Database) PpidDataApprovalHistoriesRepository {
	return &ppidDataApprovalHistoriesRepository{
		DB: db,
	}
}

// implement interface of IPpidDataApprovalHistoriesRepository
func (_i *ppidDataApprovalHistoriesRepository) GetAll() (ppidDataApprovalHistories []*entity.PpidDataApprovalHistories, err error) {
	if err := _i.DB.DB.Find(&ppidDataApprovalHistories).
		Where(&entity.PpidDataApprovalHistories{IsActive: true}).Error; err != nil {
		return nil, err
	}

	return ppidDataApprovalHistories, nil
}

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

	return ppidDataApprovalHistories, nil
}

func (_i *ppidDataApprovalHistoriesRepository) FindByPpidData(ppidDataId uint) (ppidDataApprovalHistories []*entity.PpidDataApprovalHistories, err error) {
	if err := _i.DB.DB.Find(&ppidDataApprovalHistories).
		Where(&entity.PpidDataApprovalHistories{PpidDataId: ppidDataId, IsActive: true}).Error; err != nil {
		return nil, err
	}

	return ppidDataApprovalHistories, nil
}

func (_i *ppidDataApprovalHistoriesRepository) Create(ppidDataApprovalHistories *entity.PpidDataApprovalHistories) (err error) {
	return _i.DB.DB.Create(ppidDataApprovalHistories).Error
}

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

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