package datajson

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

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

type JsonNewsChannelRepository struct {
	Directory string
}

const NC_PREFIX = "news_channel_"

func NewJsonNewsChannelRepository(directory string) *JsonNewsChannelRepository {
	return &JsonNewsChannelRepository{
		Directory: directory,
	}
}

func (r *JsonNewsChannelRepository) GetAll() ([]*entity.NewsChannel, error) {
	files, err := os.ReadDir(r.Directory)
	if err != nil {
		return nil, err
	}

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

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

		entities = append(entities, &entity)
	}

	return entities, nil
}

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

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

	return &entity, nil
}

func (r *JsonNewsChannelRepository) Create(entity *entity.NewsChannel) 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, NC_PREFIX, entity.Id), data, 0644)
	return err
}

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

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