package repository

import (
	"github.com/rs/zerolog"
	"go-humas-be/app/database"
	"go-humas-be/app/database/entity"
	"go-humas-be/app/module/ppid_data_files/request"
	"go-humas-be/utils/paginator"
)

type ppidDataFilesRepository struct {
	DB  *database.Database
	Log zerolog.Logger
}

// PpidDataFilesRepository define interface of IPpidDataFilesRepository
type PpidDataFilesRepository interface {
	GetAll(req request.PpidDataFilesQueryRequest) (ppidDataFiless []*entity.PpidDataFiles, paging paginator.Pagination, err error)
	FindOne(id uint) (ppidDataFiles *entity.PpidDataFiles, err error)
	FindByFilename(filename string) (ppidDataFiles *entity.PpidDataFiles, err error)
	FindByPpidData(ppidDataId uint) (ppidDataFiless []*entity.PpidDataFiles, err error)
	Create(ppidDataFiles *entity.PpidDataFiles) (err error)
	Update(id uint, ppidDataFiles *entity.PpidDataFiles) (err error)
	Delete(id uint) (err error)
}

func NewPpidDataFilesRepository(db *database.Database, logger zerolog.Logger) PpidDataFilesRepository {
	return &ppidDataFilesRepository{
		DB:  db,
		Log: logger,
	}
}

// implement interface of IPpidDataFilesRepository
func (_i *ppidDataFilesRepository) GetAll(req request.PpidDataFilesQueryRequest) (ppidDataFiless []*entity.PpidDataFiles, paging paginator.Pagination, err error) {
	var count int64

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

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

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

	paging = *req.Pagination

	return
}

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

	return ppidDataFiles, nil
}

func (_i *ppidDataFilesRepository) FindByFilename(filename string) (ppidDataFiles *entity.PpidDataFiles, err error) {

	if err := _i.DB.DB.Where("file_name = ?", filename).First(&ppidDataFiles).Error; err != nil {
		return nil, err
	}

	return ppidDataFiles, nil
}

func (_i *ppidDataFilesRepository) FindByPpidData(ppidDataId uint) (ppidDataFiles []*entity.PpidDataFiles, err error) {
	if err := _i.DB.DB.Where("ppid_data_id = ?", ppidDataId).Find(&ppidDataFiles).Error; err != nil {
		return nil, err
	}

	return ppidDataFiles, nil
}

func (_i *ppidDataFilesRepository) Create(ppidDataFiles *entity.PpidDataFiles) (err error) {
	return _i.DB.DB.Create(ppidDataFiles).Error
}

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

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