package repository

import (
	"jaecoo-be/app/database"
	"jaecoo-be/app/database/entity"
	"jaecoo-be/app/module/approval_histories/request"
	"jaecoo-be/utils/paginator"

	"github.com/rs/zerolog"
)

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

// ApprovalHistoriesRepository define interface
type ApprovalHistoriesRepository interface {
	GetAll(req request.ApprovalHistoriesQueryRequest) (histories []*entity.ApprovalHistories, paging paginator.Pagination, err error)
	FindOne(id uint) (history *entity.ApprovalHistories, err error)
	Create(history *entity.ApprovalHistories) (historyReturn *entity.ApprovalHistories, err error)
	GetByModule(moduleType string, moduleId uint) (histories []*entity.ApprovalHistories, err error)
}

func NewApprovalHistoriesRepository(db *database.Database, logger zerolog.Logger) ApprovalHistoriesRepository {
	return &approvalHistoriesRepository{
		DB:  db,
		Log: logger,
	}
}

// GetAll implement interface
func (_i *approvalHistoriesRepository) GetAll(req request.ApprovalHistoriesQueryRequest) (histories []*entity.ApprovalHistories, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.ApprovalHistories{})

	if req.ModuleType != nil && *req.ModuleType != "" {
		query = query.Where("module_type = ?", *req.ModuleType)
	}
	if req.ModuleId != nil {
		query = query.Where("module_id = ?", *req.ModuleId)
	}
	if req.StatusId != nil {
		query = query.Where("status_id = ?", *req.StatusId)
	}
	if req.Action != nil && *req.Action != "" {
		query = query.Where("action = ?", *req.Action)
	}
	if req.ApprovedBy != nil {
		query = query.Where("approved_by = ?", *req.ApprovedBy)
	}

	query.Count(&count)

	if req.Pagination.SortBy != "" {
		direction := "ASC"
		if req.Pagination.Sort == "desc" {
			direction = "DESC"
		}
		query.Order("created_at " + direction)
	} else {
		query.Order("created_at DESC")
	}

	req.Pagination.Count = count
	pagingPtr := paginator.Paging(&req.Pagination)

	err = query.Offset(pagingPtr.Offset).Limit(pagingPtr.Limit).Find(&histories).Error
	if err != nil {
		return
	}

	paging = *pagingPtr
	return
}

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

func (_i *approvalHistoriesRepository) Create(history *entity.ApprovalHistories) (historyReturn *entity.ApprovalHistories, err error) {
	result := _i.DB.DB.Create(history)
	return history, result.Error
}

func (_i *approvalHistoriesRepository) GetByModule(moduleType string, moduleId uint) (histories []*entity.ApprovalHistories, err error) {
	err = _i.DB.DB.Where("module_type = ? AND module_id = ?", moduleType, moduleId).
		Order("created_at DESC").
		Find(&histories).Error
	return
}
