package web

import (
	"io/fs"
	"path/filepath"
	"strings"

	"github.com/gofiber/fiber/v3"
	"github.com/gofiber/utils/v2"
)

func (s *WebServer) routeGetVersion(c fiber.Ctx) error {
	files := []string{}
	error := filepath.WalkDir(config.Path, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}

		if d.IsDir() {
			return nil
		}

		if strings.HasPrefix(path, filepath.Join(config.Path, ".git/")) {
			return nil
		}

		if strings.HasPrefix(path, filepath.Join(config.Path, "boot/")) {
			return nil
		}

		if strings.ToLower(path) == strings.ToLower(filepath.Join(config.Path, "README.md")) {
			return nil
		}

		if strings.ToLower(path) == strings.ToLower(filepath.Join(config.Path, "main.js")) {
			return nil
		}

		if strings.ToLower(path) == strings.ToLower(filepath.Join(config.Path, "project.json")) {
			return nil
		}

		if path == config.Path {
			return nil
		}

		files = append(files, strings.Replace(path, config.Path+"/", "", -1))
		return nil
	})
	if error != nil {
		return error
	}

	files = append(files, "version.txt")
	return c.JSON(map[string]interface{}{
		"version": config.Version,
		"files":   files,
	})
}

func (s *WebServer) routeGetVersionFile(c fiber.Ctx) error {
	file := c.Params("+")
	c.Response().Header.SetCanonical(
		utils.UnsafeBytes(fiber.HeaderContentDisposition),
		utils.UnsafeBytes(`attachment;`),
	)
	if file == "version.txt" {
		return c.SendString(config.Version)
	}
	return c.SendFile(filepath.Join(config.Path, file), false)
}
