package services

import (
	"fmt"

	datasql "gitlab.ost.ch/marketminds/marketminds/pkg/data/sql"
	"gitlab.ost.ch/marketminds/marketminds/pkg/entity"
)

func (s *Service) GetNews(pageSize int, offset int) ([]*entity.NewsItem, error) {
	session := datasql.NewSqlRepository(s.SqlInstance)

	newsItemPaging, err := session.GetNewsItemPaging(pageSize, offset)

	if err != nil {
		return nil, err
	}

	for _, newsItem := range newsItemPaging {
		newsItem.NewsChannel, err = session.GetNewsChannelById(fmt.Sprint(newsItem.NewsChannelId))
		if err != nil {
			fmt.Println("Error getting news channel:", err)
			continue
		}

		newsItem.SentimentResult, err = session.GetSentimentResultByNewsItemId(newsItem.Id)
		if err != nil {
			fmt.Println("Error getting sentiment result:", err)
			continue
		}

		nerResult, err := session.GetNERResultByNewsItemId(newsItem.Id)
		if err != nil {
			fmt.Println("Error getting NER result:", err)
			continue
		}

		for _, ner := range nerResult {
			ner.NamedEntity, err = session.GetNamedEntityByName(ner.NamedEntityId)
			if err != nil {
				fmt.Println("Error getting named entity:", err)
				continue
			}
		}

		newsItem.NERResult = nerResult
	}

	return newsItemPaging, nil
}

func (s *Service) GetNewsItemById(id string) (*entity.NewsItem, error) {
	session := datasql.NewSqlRepository(s.SqlInstance)

	newsItem, err := session.GetNewsItemById(id)

	if err != nil {
		return nil, err
	}

	newsItem.NewsChannel, err = session.GetNewsChannelById(fmt.Sprint(newsItem.NewsChannelId))
	if err != nil {
		fmt.Println("Error getting news channel:", err)
	}

	newsItem.SentimentResult, err = session.GetSentimentResultByNewsItemId(newsItem.Id)
	if err != nil {
		fmt.Println("Error getting sentiment result:", err)
	}

	nerResult, err := session.GetNERResultByNewsItemId(newsItem.Id)
	if err != nil {
		fmt.Println("Error getting NER result:", err)
	}

	for _, ner := range nerResult {
		ner.NamedEntity, err = session.GetNamedEntityByName(ner.NamedEntityId)
		if err != nil {
			fmt.Println("Error getting named entity:", err)
			continue
		}
	}

	newsItem.NERResult = nerResult

	return newsItem, nil
}
