package mapper

import (
	"github.com/rs/zerolog"
	"go-humas-be/app/database/entity"
	ppidDataCategoriesRepository "go-humas-be/app/module/ppid_data_categories/repository"
	ppidDataFilesMapper "go-humas-be/app/module/ppid_data_files/mapper"
	ppidDataFilesRepository "go-humas-be/app/module/ppid_data_files/repository"
	ppidDataFilesResponse "go-humas-be/app/module/ppid_data_files/response"
	res "go-humas-be/app/module/ppid_datas/response"
	usersRepository "go-humas-be/app/module/users/repository"
)

func PpidDatasResponseMapper(
	log zerolog.Logger,
	ppidDataCategoriesRepo ppidDataCategoriesRepository.PpidDataCategoriesRepository,
	ppidDataFilesRepo ppidDataFilesRepository.PpidDataFilesRepository,
	usersRepo usersRepository.UsersRepository,
	ppidDatasReq *entity.PpidDatas,
) (ppidDatasRes *res.PpidDatasResponse) {
	if ppidDatasReq != nil {
		findCategory, _ := ppidDataCategoriesRepo.FindOne(ppidDatasReq.CategoryId)
		categoryName := ""
		if findCategory != nil {
			categoryName = findCategory.Title
		}

		findUser, _ := usersRepo.FindOne(*ppidDatasReq.CreatedById)
		createdByName := ""
		if findUser != nil {
			createdByName = findUser.Fullname
		}

		ppidDataFiles, _ := ppidDataFilesRepo.FindByPpidData(ppidDatasReq.ID)

		var ppidDataFilesArr []*ppidDataFilesResponse.PpidDataFilesResponse
		if len(ppidDataFiles) > 0 {
			for _, result := range ppidDataFiles {
				ppidDataFilesArr = append(ppidDataFilesArr, ppidDataFilesMapper.PpidDataFilesResponseMapper(result))
			}
		}

		//log.Info().Str("timestamp", time.Now().
		//	Format(time.RFC3339)).Str("Service:PpidDatasResponseMapper", "UserInfo:PpidData").
		//	Interface("payload", ppidDataFiles).Msg("")

		ppidDatasRes = &res.PpidDatasResponse{
			ID:            ppidDatasReq.ID,
			Title:         ppidDatasReq.Title,
			Description:   ppidDatasReq.Description,
			Slug:          ppidDatasReq.Slug,
			CategoryId:    ppidDatasReq.CategoryId,
			CategoryName:  &categoryName,
			CreatedById:   ppidDatasReq.CreatedById,
			CreatedByName: &createdByName,
			StatusId:      ppidDatasReq.StatusId,
			IsPublish:     ppidDatasReq.IsPublish,
			PublishedAt:   ppidDatasReq.PublishedAt,
			IsActive:      ppidDatasReq.IsActive,
			CreatedAt:     ppidDatasReq.CreatedAt,
			UpdatedAt:     ppidDatasReq.UpdatedAt,

			PpidDataFiles: ppidDataFilesArr,
		}
	}
	return ppidDatasRes
}
