package tsgenerator

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	tsrpc "server/pkg/ts-rpc"
)

func TsGenerate() (string, error) {
	path := "GeneratedCode"

	if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
		err := os.Mkdir(path, os.ModePerm)
		if err != nil {
			return "", fmt.Errorf("create GeneratedCode directory: %w", err)
		}
	}

	d, err := os.Open(path)
	if err != nil {
		return "", fmt.Errorf("open GeneratedCode directory: %w", err)
	}
	defer d.Close()
	names, err := d.Readdirnames(-1)
	if err != nil {
		return "", fmt.Errorf("read GeneratedCode directory: %w", err)
	}
	for _, name := range names {
		err = os.RemoveAll(filepath.Join(path, name))
		if err != nil {
			return "", fmt.Errorf("remove GeneratedCode directory content: %w", err)
		}
	}

	err = tsrpc.GetTSSource()
	if err != nil {
		return "", fmt.Errorf("get ts source: %w", err)
	}

	return "Generation OK \n\n", nil
}
