package fs

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"

	"source.toby3d.me/toby3d/home/internal/domain"
	"source.toby3d.me/toby3d/home/internal/static"
)

type fileServerStaticRepository struct {
	store fs.FS
}

func (repo *fileServerStaticRepository) Create(_ context.Context, s domain.Static, p string) (bool, error) {
	f, err := os.OpenFile(filepath.Clean(p), os.O_WRONLY, os.ModePerm)
	if err != nil {
		return false, fmt.Errorf("cannot open static for writing: %w", err)
	}
	defer f.Close()

	if _, err = io.Copy(f, &s); err != nil {
		return false, fmt.Errorf("cannot copy static: %w", err)
	}

	return true, nil
}

func (repo *fileServerStaticRepository) Get(_ context.Context, p string) (*domain.Static, error) {
	info, err := fs.Stat(repo.store, p)
	if err != nil {
		return nil, fmt.Errorf("cannot stat static on path '%s': %w", p, err)
	}

	f, err := repo.store.Open(p)
	if err != nil {
		return nil, fmt.Errorf("cannot open static on path '%s': %w", p, err)
	}
	defer f.Close()

	content, err := io.ReadAll(f)
	if err != nil {
		return nil, fmt.Errorf("cannot copy opened '%s' static contents into buffer: %w", p, err)
	}

	return domain.NewStatic(bytes.NewReader(content), info.ModTime(), info.Name()), nil
}

func (repo *fileServerStaticRepository) Delete(_ context.Context, p string) (bool, error) {
	p = filepath.Clean(p)

	_, err := fs.Stat(repo.store, p)
	if err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			return false, nil
		}

		return false, fmt.Errorf("cannot open static for writing: %w", err)
	}

	if err = os.RemoveAll(p); err != nil {
		return false, fmt.Errorf("cannot remove static: %w", err)
	}

	return true, nil
}

// NewFileServerStaticRepository creates a new FS repository for static files
// which must be uploaded and used as is.
func NewFileServerStaticRepository(store fs.FS) static.Repository {
	return &fileServerStaticRepository{
		store: store,
	}
}
