package datajson

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

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

type JsonNERResultRepository struct {
	Directory string
}

const NR_PREFIX = "ner_result_"

func NewJsonNERResultRepository(directory string) *JsonNERResultRepository {
	return &JsonNERResultRepository{
		Directory: directory,
	}
}

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

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

	return &entity, nil
}

func (r *JsonNERResultRepository) Create(entity *entity.NERResult) 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, NR_PREFIX, entity.Id), data, 0644)
	return err
}

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

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