package mapper

import (
	"web-qudo-be/app/database/entity"
	articleCategoriesMapper "web-qudo-be/app/module/article_categories/mapper"
	articleCategoriesRepository "web-qudo-be/app/module/article_categories/repository"
	articleCategoriesResponse "web-qudo-be/app/module/article_categories/response"
	articleCategoryDetailsRepository "web-qudo-be/app/module/article_category_details/repository"
	articleFilesMapper "web-qudo-be/app/module/article_files/mapper"
	articleFilesRepository "web-qudo-be/app/module/article_files/repository"
	articleFilesResponse "web-qudo-be/app/module/article_files/response"
	res "web-qudo-be/app/module/articles/response"
	usersRepository "web-qudo-be/app/module/users/repository"

	"github.com/google/uuid"
	"github.com/rs/zerolog"
)

func ArticlesResponseMapper(
	log zerolog.Logger,
	host string,
	clientId *uuid.UUID,
	articlesReq *entity.Articles,
	articleCategoriesRepo articleCategoriesRepository.ArticleCategoriesRepository,
	articleCategoryDetailsRepo articleCategoryDetailsRepository.ArticleCategoryDetailsRepository,
	articleFilesRepo articleFilesRepository.ArticleFilesRepository,
	usersRepo usersRepository.UsersRepository,
) (articlesRes *res.ArticlesResponse) {

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

	categoryName := ""
	articleCategories, _ := articleCategoryDetailsRepo.FindByArticleId(articlesReq.ID)
	var articleCategoriesArr []*articleCategoriesResponse.ArticleCategoriesResponse
	if articleCategories != nil && len(articleCategories) > 0 {
		for _, result := range articleCategories {
			articleCategoriesArr = append(articleCategoriesArr, articleCategoriesMapper.ArticleCategoriesResponseMapper(result.Category, host))
		}
		log.Info().Interface("articleCategoriesArr", articleCategoriesArr).Msg("")
	}

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

	// Calculate PublishStatus based on conditions
	publishStatus := "Cancel" // Default status

	if articlesReq.IsPublish != nil && *articlesReq.IsPublish {
		// Published: isPublish = true
		publishStatus = "Published"
	} else if articlesReq.PublishSchedule != nil && *articlesReq.PublishSchedule != "" {
		// On Schedule: has publishSchedule and isPublish = false
		if articlesReq.IsPublish == nil || !*articlesReq.IsPublish {
			publishStatus = "On Schedule"
		}
	} else if articlesReq.IsPublish != nil && !*articlesReq.IsPublish &&
		articlesReq.IsDraft != nil && !*articlesReq.IsDraft {
		// Cancel: isPublish = false and isDraft = false
		publishStatus = "Cancel"
	}

	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,
			CategoryId:        articlesReq.CategoryId,
			AiArticleId:       articlesReq.AiArticleId,
			CategoryName:      categoryName,
			PageUrl:           articlesReq.PageUrl,
			CreatedById:       articlesReq.CreatedById,
			CreatedByName:     &createdByName,
			ShareCount:        articlesReq.ShareCount,
			ViewCount:         articlesReq.ViewCount,
			CommentCount:      articlesReq.CommentCount,
			OldId:             articlesReq.OldId,
			StatusId:          articlesReq.StatusId,
			IsDraft:           articlesReq.IsDraft,
			DraftedAt:         articlesReq.DraftedAt,
			IsBanner:          articlesReq.IsBanner,
			IsPublish:         articlesReq.IsPublish,
			PublishSchedule:   articlesReq.PublishSchedule,
			PublishedAt:       articlesReq.PublishedAt,
			PublishStatus:     publishStatus,
			IsActive:          articlesReq.IsActive,
			Source:            articlesReq.Source,
			CustomCreatorName: articlesReq.CustomCreatorName,
			CreatedAt:         articlesReq.CreatedAt,
			UpdatedAt:         articlesReq.UpdatedAt,
			ArticleFiles:      articleFilesArr,
			ArticleCategories: articleCategoriesArr,
		}

		if articlesReq.ThumbnailName != nil {
			articlesRes.ThumbnailUrl = host + "/articles/thumbnail/viewer/" + *articlesReq.ThumbnailName
		}
	}

	return articlesRes
}
