package model

import (
	"bufio"
	"io"
	"os"
	"path"

	"github.com/google/uuid"
)

type AttachmentStore struct {
	basePath string
}

func NewAttachmentStore(basePath string) AttachmentStore {
	_, err := os.Stat(basePath)
	if os.IsNotExist(err) {
		os.MkdirAll(basePath, 0755)
	}

	return AttachmentStore{
		basePath: basePath,
	}
}

func (s *AttachmentStore) FetchAttachment(guid string) (io.Reader, error) {
	fullPath := path.Join(s.basePath, guid)
	f, err := os.Open(fullPath)
	if err != nil {
		return nil, err
	}

	return bufio.NewReader(f), nil
}

func (s *AttachmentStore) StoreAttachment(filename string, reader io.Reader) (*string, error) {
	// Generate GUID
	guid := uuid.New().String()

	fullPath := path.Join(s.basePath, guid)
	f, err := os.OpenFile(fullPath, os.O_CREATE|os.O_WRONLY, 0755)
	if err != nil {
		return nil, err
	}

	r := bufio.NewReader(reader)
	w := bufio.NewWriter(f)
	_, err = w.ReadFrom(r)

	return &guid, err
}

func (s *AttachmentStore) DeleteAttachment(guid string) error {
	fullPath := path.Join(s.basePath, guid)
	return os.Remove(fullPath)
}
