package story_storage

import (
	"context"
	"encoding/json"
	"evening_detective/internal/services/story_service"
	"evening_detective/internal/services/story_service/models"
	"fmt"
	"log"
	"os"
)

type fileService struct {
	filepath string
}

func NewFileStoryStorage(filepath string) story_service.IStoryStorage {
	return &fileService{
		filepath: filepath,
	}
}

func (s *fileService) Load(ctx context.Context) (*models.Story, error) {
	data, err := os.ReadFile(s.filepath)
	if err != nil {
		return nil, fmt.Errorf("story file %s not found", s.filepath)
	}
	log.Printf("load story from: %s", s.filepath)
	story := &models.Story{}
	if err := json.Unmarshal(data, story); err != nil {
		return nil, err
	}
	return story, nil
}

func (s *fileService) Save(ctx context.Context, story *models.Story) error {
	data, err := json.Marshal(story)
	if err != nil {
		return err
	}
	if err := os.WriteFile(s.filepath, data, 0x777); err != nil {
		return err
	}
	log.Printf("save story to: %s", s.filepath)
	return nil
}
