package file

import (
	"fmt"
	"io"
	//"net/http"
	"os"

	"github.com/google/uuid"
	"github.com/rs/zerolog/log"
	"source.gleipnir.technology/Gleipnir/nidus-sync/config"
	"source.gleipnir.technology/Gleipnir/nidus-sync/lint"
)

func CreateDirectories() error {
	for _, subdir := range collectionToSubdir {
		path := config.FilesDirectory + "/" + subdir
		_, err := os.Stat(path)
		if err == nil {
			continue
		}
		err = os.MkdirAll(path, 0750)
		if err != nil {
			return fmt.Errorf("Failed to create userfile directory '%s': %w", path, err)
		}
	}
	return nil
}
func FileContentWrite(body io.Reader, collection Collection, uid uuid.UUID) error {
	// Create file in configured directory
	filepath := fileContentPathUUID(collection, uid)
	dst, err := os.Create(filepath)
	if err != nil {
		log.Error().Err(err).Str("filepath", filepath).Msg("Failed to create upload file")
		return fmt.Errorf("Failed to create upload file at %s: %v", filepath, err)
	}
	defer lint.LogOnErr(dst.Close, "close dst file")

	// Copy rest of request body to file
	_, err = io.Copy(dst, body)
	if err != nil {
		return fmt.Errorf("Unable to save file to copy file content to %s: %v", filepath, err)
	}
	log.Info().Str("filepath", filepath).Msg("Save upload file content")
	return nil
}

func NewFileReader(collection Collection, uid uuid.UUID) (io.Reader, error) {
	path := fileContentPathUUID(collection, uid)
	return os.Open(path)
}
