package datajson

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

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

type JsonNamedEntityRepository struct {
	Directory string
}

const NE_PREFIX = "named_entity_"

func NewJsonNamedEntityRepository(directory string) *JsonNamedEntityRepository {
	return &JsonNamedEntityRepository{
		Directory: directory,
	}
}

func (r *JsonNamedEntityRepository) GetByName(name string) (*entity.NamedEntity, error) {
	data, err := os.ReadFile(fmt.Sprintf("%s/%s%s.json", r.Directory, NE_PREFIX, name))
	if err != nil {
		return nil, err
	}

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

	return &entity, nil
}

func (r *JsonNamedEntityRepository) Create(entity *entity.NamedEntity) 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%s.json", r.Directory, NE_PREFIX, entity.Name), data, 0644)
	return err
}

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

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