package datajson

import (
	"encoding/json"
	"fmt"
	"os"

	"gitlab.ost.ch/marketminds/marketminds/pkg/entity"
)

type JsonNewsItemRepository struct {
	Directory string
}

const NI_PREFIX = "news_item_"

func NewJsonNewsItemRepository(directory string) *JsonNewsItemRepository {
	return &JsonNewsItemRepository{
		Directory: directory,
	}
}

func (r *JsonNewsItemRepository) GetAllByNewsChannelId(newsChannelId int64) ([]*entity.NewsItem, error) {
	files, err := os.ReadDir(r.Directory)
	if err != nil {
		return nil, err
	}

	var entities []*entity.NewsItem
	for _, file := range files {
		data, err := os.ReadFile(fmt.Sprintf("%s/%s%s", r.Directory, NI_PREFIX, file.Name()))
		if err != nil {
			return nil, err
		}

		var entity entity.NewsItem
		err = json.Unmarshal(data, &entity)
		if err != nil {
			return nil, err
		}

		if entity.NewsChannelId == newsChannelId {
			entities = append(entities, &entity)
		}
	}

	return entities, nil
}

func (r *JsonNewsItemRepository) GetById(id int) (*entity.NewsItem, error) {
	data, err := os.ReadFile(fmt.Sprintf("%s/%s%d.json", r.Directory, NI_PREFIX, id))
	if err != nil {
		return nil, err
	}

	var entity entity.NewsItem
	err = json.Unmarshal(data, &entity)
	if err != nil {
		return nil, err
	}

	return &entity, nil
}

func (r *JsonNewsItemRepository) Create(entity *entity.NewsItem) error {
	data, err := json.Marshal(entity)
	if err != nil {
		return err
	}

	if err := os.MkdirAll(r.Directory, 0755); err != nil {
		return err
	}

	err = os.WriteFile(fmt.Sprintf("%s/%s%d.json", r.Directory, NI_PREFIX, entity.Id), data, 0644)
	return err
}

func (r *JsonNewsItemRepository) Update(entity *entity.NewsItem) error {
	// Similar to Create
	return r.Create(entity)
}

func (r *JsonNewsItemRepository) Delete(id int) error {
	err := os.Remove(fmt.Sprintf("%s/%s%d.json", r.Directory, NI_PREFIX, id))
	return err
}
