package mapper

import (
	"github.com/rs/zerolog"
	"go-humas-be/app/database/entity"
	articleFilesMapper "go-humas-be/app/module/article_files/mapper"
	articleFilesRepository "go-humas-be/app/module/article_files/repository"
	articleFilesResponse "go-humas-be/app/module/article_files/response"
	res "go-humas-be/app/module/articles/response"
	usersRepository "go-humas-be/app/module/users/repository"
)

func ArticlesResponseMapper(
	log zerolog.Logger,
	articlesReq *entity.Articles,
	articleFilesRepo articleFilesRepository.ArticleFilesRepository,
	usersRepo usersRepository.UsersRepository,
) (articlesRes *res.ArticlesResponse) {
	thumbnailUrl := "/articles/thumbnail/viewer/"
	if articlesReq.ThumbnailName != nil {
		thumbnailUrl += *articlesReq.ThumbnailName
	}

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

	articleFiles, _ := articleFilesRepo.FindByArticle(articlesReq.ID)
	var articleFilesArr []*articleFilesResponse.ArticleFilesResponse
	if articleFiles != nil && len(articleFiles) > 0 {
		for _, result := range articleFiles {
			articleFilesArr = append(articleFilesArr, articleFilesMapper.ArticleFilesResponseMapper(result))
		}
	}

	if articlesReq != nil {
		articlesRes = &res.ArticlesResponse{
			ID:              articlesReq.ID,
			Title:           articlesReq.Title,
			Slug:            articlesReq.Slug,
			Description:     articlesReq.Description,
			HtmlDescription: articlesReq.HtmlDescription,
			TypeId:          articlesReq.TypeId,
			Tags:            articlesReq.Tags,
			ThumbnailUrl:    thumbnailUrl,
			PageUrl:         articlesReq.PageUrl,
			CreatedById:     articlesReq.CreatedById,
			CreatedByName:   &createdByName,
			ShareCount:      articlesReq.ShareCount,
			ViewCount:       articlesReq.ViewCount,
			DownloadCount:   articlesReq.DownloadCount,
			StatusId:        articlesReq.StatusId,
			IsPublish:       articlesReq.IsPublish,
			PublishedAt:     articlesReq.PublishedAt,
			IsActive:        articlesReq.IsActive,
			CreatedAt:       articlesReq.CreatedAt,
			UpdatedAt:       articlesReq.UpdatedAt,
			ArticleFiles:    articleFilesArr,
		}
	}

	return articlesRes
}
